﻿// Copyright (C) 2014 - 2016 Stephan Bouchard - All Rights Reserved
// Modified by Salomon Zwecker (for Better UI)
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms

using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.Collections;
using TMPro;
using TMPro.EditorUtilities;
using TheraBytes.BetterUi;

namespace TheraBytes.BetterUi.Editor
{
    internal enum ColorGradientMode
    {
        Single,
        HorizontalGradient,
        VerticalGradient,
        FourCornersGradient,
    }


    [CustomEditor(typeof(BetterTextMeshProUGUI)), CanEditMultipleObjects]
    public class BetterTextMeshProEditor : UnityEditor.Editor
    {
        [MenuItem("CONTEXT/TextMeshProUGUI/♠ Make Better")]
        public static void MakeBetter(MenuCommand command)
        {
            TextMeshProUGUI ctrl = command.context as TextMeshProUGUI;

            float fontSize = ctrl.fontSize;
            float fontSizeMin = ctrl.fontSizeMin;
            float fontSizeMax = ctrl.fontSizeMax;
            Vector4 margin = ctrl.margin;

            Vector2 rectSize = ctrl.rectTransform.sizeDelta;
            Vector2 rectPos = ctrl.rectTransform.anchoredPosition;

            var newCtrl = Betterizer.MakeBetter<TextMeshProUGUI, BetterTextMeshProUGUI>(ctrl, 
                "m_mesh", "m_subTextObjects", "m_fontSharedMaterials", "m_fontMaterials", "m_textInfo");
            var better = newCtrl as BetterTextMeshProUGUI;

            if (newCtrl != null)
            {
                newCtrl.SetCharArray(newCtrl.text.ToCharArray());

                if (better != null)
                {
                    better.FontSizer.SetSize(fontSize);
                    better.MinFontSizer.SetSize(fontSizeMin);
                    better.MaxFontSizer.SetSize(fontSizeMax);
                    better.MarginSizer.SetSize(new Margin(margin));

                    better.Fitting = BetterText.FittingMode.StayInBounds;
                }

                newCtrl.ClearMesh();
                //newCtrl.textInfo.textComponent = newCtrl;
                //newCtrl.textInfo.meshInfo[0].mesh = newCtrl.mesh;
                //newCtrl.SetAllDirty();
                //newCtrl.UpdateFontAsset();
                //newCtrl.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
                //newCtrl.UpdateMeshPadding();
                //newCtrl.UpdateGeometry(newCtrl.mesh, 0);

                //newCtrl.Rebuild(CanvasUpdate.PreRender);

                newCtrl.rectTransform.sizeDelta = rectSize;
                newCtrl.rectTransform.anchoredPosition = rectPos;
            }
        }

        private class Foldout
        {
            // Track Inspector foldout panel states, globally.
            public static bool textInput = true;
            public static bool fontSettings = true;
            public static bool extraSettings = false;
            public static bool shadowSetting = false;
            public static bool materialEditor = true;
            //internal static bool autoSizeSettings;
        }

        //private static int m_eventID;

        private const string k_UndoRedo = "UndoRedoPerformed";

        private GUIStyle toggleStyle;
        public int selAlignGrid_A = 0;
        public int selAlignGrid_B = 0;

        #region serialized properties

        // Serialized Properties
        private SerializedProperty text_prop;

        // Right to Left properties
        private SerializedProperty isRightToLeft_prop;
        private string m_RTLText;

        private SerializedProperty fontAsset_prop;

        private SerializedProperty fontSharedMaterial_prop;
        private Material[] m_materialPresets;
        private string[] m_materialPresetNames;
        private int m_materialPresetSelectionIndex;
        private bool m_isPresetListDirty;

        private SerializedProperty fontStyle_prop;

        // Color Properties
        private SerializedProperty fontColor_prop;
        private SerializedProperty enableVertexGradient_prop;
        private SerializedProperty fontColorGradient_prop;
        private SerializedProperty fontColorGradientPreset_prop;
        private SerializedProperty overrideHtmlColor_prop;

        private SerializedProperty fontSize_prop;
        //private SerializedProperty fontSizeBase_prop;

        //private SerializedProperty autoSizing_prop;
        private SerializedProperty fontSizeMin_prop;
        private SerializedProperty fontSizeMax_prop;
        //private SerializedProperty charSpacingMax_prop;
        private SerializedProperty lineSpacingMax_prop;
        private SerializedProperty charWidthMaxAdj_prop;

        private SerializedProperty characterSpacing_prop;
        private SerializedProperty wordSpacing_prop;
        private SerializedProperty lineSpacing_prop;
        private SerializedProperty paragraphSpacing_prop;

        private SerializedProperty textAlignment_prop;
        //private SerializedProperty textAlignment_prop;

        private SerializedProperty horizontalMapping_prop;
        private SerializedProperty verticalMapping_prop;
        //private SerializedProperty uvOffset_prop;
        private SerializedProperty uvLineOffset_prop;

        private SerializedProperty enableWordWrapping_prop;
        private SerializedProperty wordWrappingRatios_prop;
        private SerializedProperty textOverflowMode_prop;
        private SerializedProperty pageToDisplay_prop;
        private SerializedProperty linkedTextComponent_prop;
        private SerializedProperty isLinkedTextComponent_prop;

        private SerializedProperty enableKerning_prop;

        private SerializedProperty inputSource_prop;
        private SerializedProperty havePropertiesChanged_prop;
        private SerializedProperty isInputPasingRequired_prop;
        private SerializedProperty isRichText_prop;

        private SerializedProperty hasFontAssetChanged_prop;

        private SerializedProperty enableExtraPadding_prop;
        private SerializedProperty checkPaddingRequired_prop;
        private SerializedProperty enableEscapeCharacterParsing_prop;
        private SerializedProperty useMaxVisibleDescender_prop;
        private SerializedProperty geometrySortingOrder_prop;

        private SerializedProperty spriteAsset_prop;

        private SerializedProperty margin_prop;

        //private SerializedProperty isMaskUpdateRequired_prop;
        //private SerializedProperty mask_prop;
        //private SerializedProperty maskOffset_prop;
        //private SerializedProperty maskOffsetMode_prop;
        //private SerializedProperty maskSoftness_prop;

        //private SerializedProperty vertexOffset_prop;

        private SerializedProperty raycastTarget_prop;

        //private SerializedProperty sortingLayerID_prop;
        //private SerializedProperty sortingOrder_prop;

        // Better UI

        private SerializedProperty fitting_prop;
        private SerializedProperty fontSizerFallback_prop;
        private SerializedProperty fontSizerList_prop;
        private SerializedProperty minFontSizerFallback_prop;
        private SerializedProperty minFontSizerList_prop;
        private SerializedProperty maxFontSizerFallback_prop;
        private SerializedProperty maxFontSizerList_prop;
        private SerializedProperty marginSizerFallback_prop;
        private SerializedProperty marginSizerList_prop;

#endregion

        private bool havePropertiesChanged = false;


        private BetterTextMeshProUGUI m_textComponent;
        private RectTransform m_rectTransform;
        //private CanvasRenderer m_canvasRenderer;
        private UnityEditor.Editor m_materialEditor;
        private Material m_targetMaterial;
        private ColorGradientMode m_colorMode = ColorGradientMode.FourCornersGradient;

        private Vector3[] m_rectCorners = new Vector3[4];
        private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };


        public void OnEnable()
        {
            //Debug.Log("New Instance of TMPRO UGUI Editor with ID " + this.GetInstanceID());

            // Initialize the Event Listener for Undo Events.
            //Undo.undoRedoPerformed += OnUndoRedo;
            //Undo.postprocessModifications += OnUndoRedoEvent;

            text_prop = serializedObject.FindProperty("m_text");
            isRightToLeft_prop = serializedObject.FindProperty("m_isRightToLeft");
            fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
            fontSharedMaterial_prop = serializedObject.FindProperty("m_sharedMaterial");

            fontStyle_prop = serializedObject.FindProperty("m_fontStyle");

            fontSize_prop = serializedObject.FindProperty("m_fontSize");
            //fontSizeBase_prop = serializedObject.FindProperty("m_fontSizeBase");

            //autoSizing_prop = serializedObject.FindProperty("m_enableAutoSizing");
            fontSizeMin_prop = serializedObject.FindProperty("m_fontSizeMin");
            fontSizeMax_prop = serializedObject.FindProperty("m_fontSizeMax");
            //charSpacingMax_prop = serializedObject.FindProperty("m_charSpacingMax");
            lineSpacingMax_prop = serializedObject.FindProperty("m_lineSpacingMax");
            charWidthMaxAdj_prop = serializedObject.FindProperty("m_charWidthMaxAdj");

            // Colors & Gradient
            fontColor_prop = serializedObject.FindProperty("m_fontColor");
            enableVertexGradient_prop = serializedObject.FindProperty("m_enableVertexGradient");
            fontColorGradient_prop = serializedObject.FindProperty("m_fontColorGradient");
            fontColorGradientPreset_prop = serializedObject.FindProperty("m_fontColorGradientPreset");
            overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");

            characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
            wordSpacing_prop = serializedObject.FindProperty("m_wordSpacing");
            lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
            paragraphSpacing_prop = serializedObject.FindProperty("m_paragraphSpacing");

            textAlignment_prop = serializedObject.FindProperty("m_textAlignment");

            horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
            verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
            //uvOffset_prop = serializedObject.FindProperty("m_uvOffset");
            uvLineOffset_prop = serializedObject.FindProperty("m_uvLineOffset");

            enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
            wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
            textOverflowMode_prop = serializedObject.FindProperty("m_overflowMode");
            pageToDisplay_prop = serializedObject.FindProperty("m_pageToDisplay");
            linkedTextComponent_prop = serializedObject.FindProperty("m_linkedTextComponent");
            isLinkedTextComponent_prop = serializedObject.FindProperty("m_isLinkedTextComponent");

            enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
            //isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
            //isOverlay_prop = serializedObject.FindProperty("m_isOverlay");

            havePropertiesChanged_prop = serializedObject.FindProperty("m_havePropertiesChanged");
            inputSource_prop = serializedObject.FindProperty("m_inputSource");
            isInputPasingRequired_prop = serializedObject.FindProperty("m_isInputParsingRequired");

            enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
            isRichText_prop = serializedObject.FindProperty("m_isRichText");
            checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
            enableEscapeCharacterParsing_prop = serializedObject.FindProperty("m_parseCtrlCharacters");
            useMaxVisibleDescender_prop = serializedObject.FindProperty("m_useMaxVisibleDescender");
            geometrySortingOrder_prop = serializedObject.FindProperty("m_geometrySortingOrder");
            spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset");

            raycastTarget_prop = serializedObject.FindProperty("m_RaycastTarget");

            margin_prop = serializedObject.FindProperty("m_margin");

            // Better UI
            fitting_prop = serializedObject.FindProperty("fitting");
            fontSizerFallback_prop = serializedObject.FindProperty("fontSizerFallback");
            minFontSizerFallback_prop = serializedObject.FindProperty("minFontSizerFallback");
            maxFontSizerFallback_prop = serializedObject.FindProperty("maxFontSizerFallback");
            marginSizerFallback_prop = serializedObject.FindProperty("marginSizerFallback");

            fontSizerList_prop = serializedObject.FindProperty("customFontSizers");
            minFontSizerList_prop = serializedObject.FindProperty("customMinFontSizers");
            maxFontSizerList_prop = serializedObject.FindProperty("customMaxFontSizers");
            marginSizerList_prop = serializedObject.FindProperty("customMarginSizers");

            //isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
            //mask_prop = serializedObject.FindProperty("m_mask");
            //maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
            //maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
            //maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
            //vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");

            //sortingLayerID_prop = serializedObject.FindProperty("m_sortingLayerID");
            //sortingOrder_prop = serializedObject.FindProperty("m_sortingOrder");

            hasFontAssetChanged_prop = serializedObject.FindProperty("m_hasFontAssetChanged");

#if !UNITY_2018_3_OR_NEWER
            // Get the UI Skin and Styles for the various Editors
            TMP_UIStyleManager.GetUIStyles();
#endif

            m_textComponent = target as BetterTextMeshProUGUI;
            m_rectTransform = m_textComponent.rectTransform;

            // Create new Material Editor if one does not exists
            m_targetMaterial = m_textComponent.fontSharedMaterial;
            if (m_targetMaterial != null)
                m_materialEditor = CreateEditor(m_targetMaterial);

            // Set material editor visibility
            if (Foldout.materialEditor)
                UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded(m_targetMaterial, true);

            // Find all Material Presets matching the current Font Asset Material
            m_materialPresetNames = GetMaterialPresets();
        }


        public void OnDisable()
        {
            //Debug.Log("OnDisable() for GUIEditor Panel called.");
            //Undo.undoRedoPerformed -= OnUndoRedo;

            // Destroy material editor if one exists
            if (m_materialEditor != null)
            {
                //Debug.Log("Destroying Inline Material Editor.");
                DestroyImmediate(m_materialEditor);
            }

            //Undo.postprocessModifications -= OnUndoRedoEvent;  
        }


        public override void OnInspectorGUI()
        {
            // Make sure Multi selection only includes TMP Text objects.
            if (IsMixSelectionTypes()) return;

            // Copy Default GUI Toggle Style
            //////if (toggleStyle == null)
            //////{
            //////    toggleStyle = new GUIStyle(GUI.skin.label);
            //////    toggleStyle.fontSize = 12;
            //////    toggleStyle.normal.textColor = TMP_UIStyleManager.Section_Label.normal.textColor;
            //////    toggleStyle.richText = true;
            //////}


            serializedObject.Update();

            Rect rect;// = EditorGUILayout.GetControlRect(false, 25);
            float labelWidth = EditorGUIUtility.labelWidth = 130f;
            float fieldWidth = EditorGUIUtility.fieldWidth;

            //////rect.y += 2;
            //////GUI.Label(rect, "<b>TEXT INPUT BOX</b>" + (Foldout.textInput ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label);
            //////if (GUI.Button(new Rect(rect.x, rect.y, rect.width - 150, rect.height), GUIContent.none, GUI.skin.label))
            //////    Foldout.textInput = !Foldout.textInput;

            //////// Toggle showing Rich Tags
            //////GUI.Label(new Rect(rect.width - 125, rect.y + 4, 125, 24), "<i>Enable RTL Editor</i>", toggleStyle);
            //////isRightToLeft_prop.boolValue = EditorGUI.Toggle(new Rect(rect.width - 10, rect.y + 3, 20, 24), GUIContent.none, isRightToLeft_prop.boolValue);
            EditorGUILayout.Space();
            GUILayout.Label("Text");

            //////if (Foldout.textInput)
            {
                // If the text component is linked, disable the text input box.
                if (isLinkedTextComponent_prop.boolValue)
                    EditorGUILayout.HelpBox("The Text Input Box is disabled due to this text component being linked to another.", MessageType.Info);
                else
                {
                    EditorGUI.BeginChangeCheck();
                    text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, GUILayout.Height(45), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));

                    if (EditorGUI.EndChangeCheck() || (isRightToLeft_prop.boolValue && (m_RTLText == null || m_RTLText == string.Empty)))
                    {
                        inputSource_prop.enumValueIndex = 0;
                        isInputPasingRequired_prop.boolValue = true;
                        havePropertiesChanged = true;

                        // Handle Left to Right or Right to Left Editor
                        if (isRightToLeft_prop.boolValue)
                        {
                            m_RTLText = string.Empty;
                            string sourceText = text_prop.stringValue;
                            // Reverse Text displayed in Text Input Box
                            for (int i = 0; i < sourceText.Length; i++)
                            {
                                m_RTLText += sourceText[sourceText.Length - i - 1];
                            }
                        }
                    }

                    if (isRightToLeft_prop.boolValue)
                    {
                        EditorGUI.BeginChangeCheck();
                        m_RTLText = EditorGUILayout.TextArea(m_RTLText, GUILayout.Height(125), GUILayout.ExpandWidth(true));
                        if (EditorGUI.EndChangeCheck())
                        {
                            // Convert RTL input
                            string sourceText = string.Empty;
                            // Reverse Text displayed in Text Input Box
                            for (int i = 0; i < m_RTLText.Length; i++)
                            {
                                sourceText += m_RTLText[m_RTLText.Length - i - 1];
                            }

                            text_prop.stringValue = sourceText;
                        }
                    }
                }
            }

            isRightToLeft_prop.boolValue = EditorGUILayout.Toggle("Enable RTL Editor", isRightToLeft_prop.boolValue);

            // FONT SETTINGS SECTION
            //////if (GUILayout.Button("<b>FONT SETTINGS</b>" + (Foldout.fontSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            //////    Foldout.fontSettings = !Foldout.fontSettings;

            GUILayout.Label("Main Settings", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            // Update list of material presets if needed.
            if (m_isPresetListDirty)
                m_materialPresetNames = GetMaterialPresets();

            if (Foldout.fontSettings)
            {
                // FONT ASSET
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(fontAsset_prop);
                if (EditorGUI.EndChangeCheck())
                {
                    havePropertiesChanged = true;
                    hasFontAssetChanged_prop.boolValue = true;

                    m_isPresetListDirty = true;
                    m_materialPresetSelectionIndex = 0;
                }


                // MATERIAL PRESET
                if (m_materialPresetNames != null)
                {
                    EditorGUI.BeginChangeCheck();
                    rect = EditorGUILayout.GetControlRect(false, 17);

                    m_materialPresetSelectionIndex = EditorGUI.Popup(rect, "Material Preset", m_materialPresetSelectionIndex, m_materialPresetNames);
                    if (EditorGUI.EndChangeCheck())
                    {
                        fontSharedMaterial_prop.objectReferenceValue = m_materialPresets[m_materialPresetSelectionIndex];
                        havePropertiesChanged = true;
                    }

                    //Make sure material preset selection index matches the selection
                    if (m_materialPresetSelectionIndex < m_materialPresetNames.Length && m_targetMaterial != m_materialPresets[m_materialPresetSelectionIndex] && !havePropertiesChanged)
                        m_isPresetListDirty = true;
                }


                // FONT STYLE
                EditorGUI.BeginChangeCheck();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PrefixLabel("Font Style");
                int styleValue = fontStyle_prop.intValue;
                
                int v1 = GUILayout.Toggle((styleValue & 1) == 1, "B", "ButtonLeft") ? 1 : 0; // Bold
                int v2 = GUILayout.Toggle((styleValue & 2) == 2, "I", "ButtonMid") ? 2 : 0; // Italics
                int v3 = GUILayout.Toggle((styleValue & 4) == 4, "U", "ButtonMid") ? 4 : 0; // Underline
                int v7 = GUILayout.Toggle((styleValue & 64) == 64, "S", "ButtonRight") ? 64 : 0; // Strikethrough
                int v4 = GUILayout.Toggle((styleValue & 8) == 8, "ab", "ButtonLeft") ? 8 : 0; // Lowercase
                int v5 = GUILayout.Toggle((styleValue & 16) == 16, "AB", "ButtonMid") ? 16 : 0; // Uppercase
                int v6 = GUILayout.Toggle((styleValue & 32) == 32, "SC", "ButtonRight") ? 32 : 0; // Smallcaps
                EditorGUILayout.EndHorizontal();

                if (EditorGUI.EndChangeCheck())
                {
                    fontStyle_prop.intValue = v1 + v2 + v3 + v4 + v5 + v6 + v7;
                    havePropertiesChanged = true;
                }

                // /////////////
                // FONT SIZE //
                // ///////////

                EditorGUI.indentLevel++;
                if (fitting_prop.intValue != (int)BetterText.FittingMode.BestFit)
                {
                    ScreenConfigConnectionHelper.DrawSizerGui("Font Size", fontSizerList_prop, ref fontSizerFallback_prop);
                }

                EditorGUILayout.PropertyField(fitting_prop);
                BetterText.FittingMode fitting = (BetterText.FittingMode)fitting_prop.intValue;
                if (fitting != BetterText.FittingMode.SizerOnly)
                {
                    // Show auto sizing options
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("Auto Size Options");
                    EditorGUIUtility.labelWidth = 24;

                    EditorGUI.indentLevel = 0;
                    EditorGUI.BeginDisabledGroup(true);
                    EditorGUI.BeginChangeCheck();
                    EditorGUILayout.PropertyField(fontSizeMin_prop, new GUIContent("Min"), GUILayout.MinWidth(46));
                    if (EditorGUI.EndChangeCheck())
                    {
                        fontSizeMin_prop.floatValue = Mathf.Min(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
                        havePropertiesChanged = true;
                    }

                    EditorGUIUtility.labelWidth = 27;
                    EditorGUI.BeginChangeCheck();
                    EditorGUILayout.PropertyField(fontSizeMax_prop, new GUIContent("Max"), GUILayout.MinWidth(49));
                    if (EditorGUI.EndChangeCheck())
                    {
                        fontSizeMax_prop.floatValue = Mathf.Max(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
                        havePropertiesChanged = true;
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUI.BeginChangeCheck();
                    EditorGUIUtility.labelWidth = 36;
                    EditorGUILayout.PropertyField(charWidthMaxAdj_prop, new GUIContent("WD%"), GUILayout.MinWidth(58));
                    EditorGUIUtility.labelWidth = 28;
                    EditorGUILayout.PropertyField(lineSpacingMax_prop, new GUIContent("Line"), GUILayout.MinWidth(50));

                    EditorGUIUtility.labelWidth = labelWidth;
                    EditorGUILayout.EndHorizontal();

                    EditorGUI.indentLevel = 2;

                    if (EditorGUI.EndChangeCheck())
                    {
                        charWidthMaxAdj_prop.floatValue = Mathf.Clamp(charWidthMaxAdj_prop.floatValue, 0, 50);
                        //charSpacingMax_prop.floatValue = Mathf.Min(0, charSpacingMax_prop.floatValue);
                        lineSpacingMax_prop.floatValue = Mathf.Min(0, lineSpacingMax_prop.floatValue);
                        havePropertiesChanged = true;
                    }

                    if (fitting == BetterText.FittingMode.BestFit)
                    {
                        EditorGUI.BeginDisabledGroup(true);
                        EditorGUILayout.PropertyField(fontSize_prop, new GUIContent("Font Size"), GUILayout.MinWidth(168), GUILayout.MaxWidth(200));
                        EditorGUI.EndDisabledGroup();
                        EditorGUIUtility.fieldWidth = fieldWidth;
                    }

                    // BETTER UI sizer
                    ScreenConfigConnectionHelper.DrawSizerGui("Min Size", minFontSizerList_prop, ref minFontSizerFallback_prop);

                    if (fitting == BetterText.FittingMode.BestFit)
                    {
                        //EditorGUILayout.PropertyField(maxFontSizerFallback_prop);
                        ScreenConfigConnectionHelper.DrawSizerGui("Max Size", maxFontSizerList_prop, ref maxFontSizerFallback_prop);
                    }
                }

                EditorGUI.indentLevel--;

                // FACE VERTEX COLOR
                EditorGUILayout.Space();
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Vertex Color"));

                // VERTEX COLOR GRADIENT
                EditorGUILayout.PropertyField(enableVertexGradient_prop, new GUIContent("Color Gradient"), GUILayout.MinWidth(140), GUILayout.MaxWidth(200));
                

                if (EditorGUI.EndChangeCheck())
                    havePropertiesChanged = true;

                // Color Mode
                if (enableVertexGradient_prop.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(fontColorGradientPreset_prop, new GUIContent("Gradient (Preset)"));

                    if (fontColorGradientPreset_prop.objectReferenceValue == null)
                    {
                        EditorGUI.BeginChangeCheck();

                        DrawColorGradient(fontColorGradient_prop.FindPropertyRelative("topLeft"),
                                          fontColorGradient_prop.FindPropertyRelative("topRight"),
                                          fontColorGradient_prop.FindPropertyRelative("bottomLeft"),
                                          fontColorGradient_prop.FindPropertyRelative("bottomRight"));
                        
                        if (EditorGUI.EndChangeCheck())
                            havePropertiesChanged = true;
                    }
                    else
                    {

                        SerializedObject obj = new SerializedObject(fontColorGradientPreset_prop.objectReferenceValue);

                        EditorGUI.BeginChangeCheck();

                        DrawColorGradient(obj.FindProperty("topLeft"),
                                          obj.FindProperty("topRight"),
                                          obj.FindProperty("bottomLeft"),
                                          obj.FindProperty("bottomRight"));

                        if (EditorGUI.EndChangeCheck())
                        {
                            obj.ApplyModifiedProperties();
                            havePropertiesChanged = true;
                            TMPro_EventManager.ON_COLOR_GRAIDENT_PROPERTY_CHANGED(fontColorGradientPreset_prop.objectReferenceValue as TMP_ColorGradient);
                        }
                    }

                    EditorGUI.indentLevel--;
                }


                EditorGUI.BeginChangeCheck();

                EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Tags"));
                
                if (EditorGUI.EndChangeCheck())
                    havePropertiesChanged = true;



                // CHARACTER, LINE & PARAGRAPH SPACING
                EditorGUILayout.Space();
                EditorGUI.BeginChangeCheck();
                int indent = EditorGUI.indentLevel;
                
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PrefixLabel("Spacing Options");
                EditorGUI.indentLevel = 0;
                EditorGUIUtility.labelWidth = 80;
                EditorGUILayout.PropertyField(characterSpacing_prop, new GUIContent("Character"), GUILayout.MinWidth(120)); //, GUILayout.MaxWidth(100));
                EditorGUILayout.PropertyField(wordSpacing_prop, new GUIContent("Word"), GUILayout.MinWidth(120)); //, GUILayout.MaxWidth(100));
                EditorGUILayout.EndHorizontal();

                EditorGUIUtility.labelWidth = labelWidth;
                EditorGUI.indentLevel = indent;

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PrefixLabel(" ");
                EditorGUI.indentLevel = 0;
                EditorGUIUtility.labelWidth = 80;
                EditorGUILayout.PropertyField(lineSpacing_prop, new GUIContent("Line"), GUILayout.MinWidth(120)); //, GUILayout.MaxWidth(100));
                EditorGUILayout.PropertyField(paragraphSpacing_prop, new GUIContent("Paragraph"), GUILayout.MinWidth(120)); //, GUILayout.MaxWidth(100));
                EditorGUILayout.EndHorizontal();

                EditorGUI.indentLevel = indent;
                EditorGUIUtility.labelWidth = labelWidth;

                if (EditorGUI.EndChangeCheck())
                {
                    havePropertiesChanged = true;
                    //isAffectingWordWrapping_prop.boolValue = true;
                }


                // TEXT ALIGNMENT
                EditorGUI.BeginChangeCheck();

                rect = EditorGUILayout.GetControlRect(false, 40);
                GUIStyle btn = new GUIStyle("ButtonMid");
                btn.margin = new RectOffset(1, 1, 1, 1);
                btn.padding = new RectOffset(1, 1, 1, 0);

                selAlignGrid_A = TMP_EditorUtility.GetHorizontalAlignmentGridValue(textAlignment_prop.intValue);
                selAlignGrid_B = TMP_EditorUtility.GetVerticalAlignmentGridValue(textAlignment_prop.intValue);

                GUI.Label(new Rect(rect.x, rect.y + 2, 100, rect.height), "Alignment");
                float columnB = EditorGUIUtility.labelWidth + 15;

                

/////////////// FIX:
///////////////
/////////////// If you are using TextMesh Pro 1.3.0 or greater,
/////////////// please comment the following two lines and uncomment the lines after that.
                
                GUIContent[] a = TMP_UIStyleManager.alignContent_A; // <- comment
                GUIContent[] b = TMP_UIStyleManager.alignContent_B; // <- comment
                
//                GUIContent[] a = TMP_UIStyleManager.alignContentA; // <- uncomment
//                GUIContent[] b = TMP_UIStyleManager.alignContentB; // <- uncomment
                
/////////////// FIX END
                
                

                selAlignGrid_A = GUI.SelectionGrid(new Rect(columnB, rect.y, 23 * 6, 0.5f * rect.height - 2), selAlignGrid_A, a, 6, btn);
                selAlignGrid_B = GUI.SelectionGrid(new Rect(columnB, rect.y + 0.5f * rect.height + 1, 23 * 6, 0.5f * rect.height - 2), selAlignGrid_B, b, 6, btn);

                if (EditorGUI.EndChangeCheck())
                {
                    int value = (0x1 << selAlignGrid_A) | (0x100 << selAlignGrid_B);
                    textAlignment_prop.intValue = value;
                    havePropertiesChanged = true;
                }

                // WRAPPING RATIOS shown if Justified mode is selected.
                EditorGUILayout.Space();

                EditorGUI.BeginChangeCheck();
                if (((_HorizontalAlignmentOptions)textAlignment_prop.intValue & _HorizontalAlignmentOptions.Justified) == _HorizontalAlignmentOptions.Justified || ((_HorizontalAlignmentOptions)textAlignment_prop.intValue & _HorizontalAlignmentOptions.Flush) == _HorizontalAlignmentOptions.Flush)
                    DrawPropertySlider("Wrap Mix (W <-> C)", wordWrappingRatios_prop);

                if (EditorGUI.EndChangeCheck())
                    havePropertiesChanged = true;


                // TEXT WRAPPING & OVERFLOW
                EditorGUI.BeginChangeCheck();

                int wrapSelection = EditorGUILayout.Popup("Wrapping", enableWordWrapping_prop.boolValue ? 1 : 0, new string[] { "Disabled", "Enabled" });
                if (EditorGUI.EndChangeCheck())
                {
                    enableWordWrapping_prop.boolValue = wrapSelection == 1 ? true : false;
                    havePropertiesChanged = true;
                    isInputPasingRequired_prop.boolValue = true;
                }


                // TEXT OVERFLOW
                EditorGUI.BeginChangeCheck();

                // Cache Reference to Linked Text Component
                TMP_Text old_LinkedComponent = linkedTextComponent_prop.objectReferenceValue as TMP_Text;

                if ((TextOverflowModes)textOverflowMode_prop.enumValueIndex == TextOverflowModes.Linked)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PropertyField(textOverflowMode_prop, new GUIContent("Overflow"));

                    EditorGUILayout.PropertyField(linkedTextComponent_prop, GUIContent.none);
                    EditorGUILayout.EndHorizontal();

                    if (GUI.changed)
                    {
                        TMP_Text linkedComponent = linkedTextComponent_prop.objectReferenceValue as TMP_Text;

                        if (linkedComponent)
                            m_textComponent.linkedTextComponent = linkedComponent;

                    }
                }
                else if ((TextOverflowModes)textOverflowMode_prop.enumValueIndex == TextOverflowModes.Page)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PropertyField(textOverflowMode_prop, new GUIContent("Overflow"));
                    EditorGUILayout.PropertyField(pageToDisplay_prop, GUIContent.none);
                    EditorGUILayout.EndHorizontal();

                    if (old_LinkedComponent)
                        m_textComponent.linkedTextComponent = null;

                }
                else
                {
                    EditorGUILayout.PropertyField(textOverflowMode_prop, new GUIContent("Overflow"));

                    if (old_LinkedComponent)
                        m_textComponent.linkedTextComponent = null;

                }

                if (EditorGUI.EndChangeCheck())
                {
                    havePropertiesChanged = true;
                    isInputPasingRequired_prop.boolValue = true;
                }


                // TEXTURE MAPPING OPTIONS
                EditorGUILayout.Space();
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(horizontalMapping_prop, new GUIContent("Horizontal Mapping"));
                EditorGUILayout.PropertyField(verticalMapping_prop, new GUIContent("Vertical Mapping"));
                if (EditorGUI.EndChangeCheck())
                {
                    havePropertiesChanged = true;
                }

                // UV OPTIONS
                if (horizontalMapping_prop.enumValueIndex > 0)
                {
                    EditorGUI.BeginChangeCheck();
                    //EditorGUILayout.BeginHorizontal();
                    //EditorGUILayout.PrefixLabel("UV Line Offset");
                    //EditorGUILayout.PropertyField(uvOffset_prop, GUIContent.none, GUILayout.MinWidth(70f));
                    //EditorGUIUtility.labelWidth = 30;
                    EditorGUILayout.PropertyField(uvLineOffset_prop, new GUIContent("Line Offset"), GUILayout.MinWidth(70f));
                    //EditorGUIUtility.labelWidth = labelWidth;
                    //EditorGUILayout.EndHorizontal();
                    if (EditorGUI.EndChangeCheck())
                    {
                        havePropertiesChanged = true;
                    }
                }


            }

            EditorGUILayout.Space();

            // EXTRA SETTINGS
            EditorGUI.indentLevel = 0;
            var origFontStyle = EditorStyles.foldout.fontStyle;
            EditorStyles.foldout.fontStyle = FontStyle.Bold;

            Foldout.extraSettings = EditorGUILayout.Foldout(Foldout.extraSettings, new GUIContent("Extra Settings"));

            EditorStyles.foldout.fontStyle = origFontStyle;


            if (Foldout.extraSettings)
            {
                EditorGUI.indentLevel++;

                EditorGUI.BeginChangeCheck();
                //DrawMaginProperty(margin_prop, "Margins");
                    ScreenConfigConnectionHelper.DrawSizerGui("Margin", marginSizerList_prop, ref marginSizerFallback_prop);
                //EditorGUILayout.PropertyField(marginSizerFallback_prop);

                if (EditorGUI.EndChangeCheck())
                {
                    m_textComponent.margin = margin_prop.vector4Value;
                    havePropertiesChanged = true;
                }

                GUILayout.Space(10);

                EditorGUI.BeginChangeCheck();

                EditorGUILayout.PropertyField(geometrySortingOrder_prop, new GUIContent("Geometry Sorting"));

                EditorGUILayout.Space();
                
                EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Rich Text"));
                if (EditorGUI.EndChangeCheck())
                    havePropertiesChanged = true;

                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(raycastTarget_prop, new GUIContent("Raycast Target"));
                if (EditorGUI.EndChangeCheck())
                {
                    // Change needs to propagate to the child sub objects.
                    Graphic[] graphicComponents = m_textComponent.GetComponentsInChildren<Graphic>();
                    for (int i = 0; i < graphicComponents.Length; i++)
                        graphicComponents[i].raycastTarget = raycastTarget_prop.boolValue;

                    havePropertiesChanged = true;
                }
                

                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(enableEscapeCharacterParsing_prop, new GUIContent("Parse Escape Characters"));
                EditorGUILayout.PropertyField(useMaxVisibleDescender_prop, new GUIContent("Visible Descender"));

                EditorGUILayout.Space();

                EditorGUILayout.PropertyField(spriteAsset_prop, new GUIContent("Sprite Asset", "The Sprite Asset used when NOT specifically referencing one using <sprite=\"Sprite Asset Name\"."), true);

                if (EditorGUI.EndChangeCheck())
                    havePropertiesChanged = true;

                // KERNING
                EditorGUILayout.Space();
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Kerning"));
                if (EditorGUI.EndChangeCheck())
                {
                    //isAffectingWordWrapping_prop.boolValue = true;
                    havePropertiesChanged = true;
                }

                // EXTRA PADDING
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding"));
                if (EditorGUI.EndChangeCheck())
                {
                    havePropertiesChanged = true;
                    checkPaddingRequired_prop.boolValue = true;
                }

                //EditorGUIUtility.labelWidth = 135;

                // EditorGUI.BeginChangeCheck();
                //EditorGUILayout.PropertyField(mask_prop);
                //EditorGUILayout.PropertyField(maskOffset_prop, true);
                //EditorGUILayout.PropertyField(maskSoftness_prop);
                //if (EditorGUI.EndChangeCheck())
                //{
                //    isMaskUpdateRequired_prop.boolValue = true;
                //    havePropertiesChanged = true;
                //}

                //EditorGUILayout.PropertyField(sortingLayerID_prop);
                //EditorGUILayout.PropertyField(sortingOrder_prop);

                // Mask Selection
            }


            

            EditorGUILayout.Space();


            // If a Custom Material Editor exists, we use it.
            if (m_targetMaterial != null) // m_canvasRenderer != null && m_canvasRenderer.GetMaterial() != null)
            {
                Material mat = m_textComponent.fontSharedMaterial; // m_canvasRenderer.GetMaterial();

                //Debug.Log(mat + "  " + m_targetMaterial);

                if (mat != m_targetMaterial)
                {
                    // Destroy previous Material Instance
                    //Debug.Log("New Material has been assigned.");
                    m_targetMaterial = mat;
                    DestroyImmediate(m_materialEditor);
                }


                if (m_materialEditor == null)
                {
                    m_materialEditor = CreateEditor(mat);
                }

                m_materialEditor.DrawHeader();


                m_materialEditor.OnInspectorGUI();
            }


            if (havePropertiesChanged)
            {
                //Debug.Log("Properties have changed.");
                havePropertiesChanged_prop.boolValue = true;
                havePropertiesChanged = false;
                EditorUtility.SetDirty(target);
            }

            serializedObject.ApplyModifiedProperties();
        }

        
        /// <summary>
        /// Method to retrieve the material presets that match the currently selected font asset.
        /// </summary>
        private string[] GetMaterialPresets()
        {
            TMP_FontAsset fontAsset = fontAsset_prop.objectReferenceValue as TMP_FontAsset;
            if (fontAsset == null) return null;

            m_materialPresets = TMP_EditorUtility.FindMaterialReferences(fontAsset);
            m_materialPresetNames = new string[m_materialPresets.Length];

            for (int i = 0; i < m_materialPresetNames.Length; i++)
            {
                m_materialPresetNames[i] = m_materialPresets[i].name;

                if (m_targetMaterial.GetInstanceID() == m_materialPresets[i].GetInstanceID())
                    m_materialPresetSelectionIndex = i;
            }

            m_isPresetListDirty = false;

            return m_materialPresetNames;
        }

        public void OnSceneGUI()
        {
            if (IsMixSelectionTypes()) return;

            // Margin Frame & Handles
            m_rectTransform.GetWorldCorners(m_rectCorners);
            Vector4 marginOffset = m_textComponent.margin;
            Vector3 lossyScale = m_rectTransform.lossyScale;

            handlePoints[0] = m_rectCorners[0] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, marginOffset.w * lossyScale.y, 0));
            handlePoints[1] = m_rectCorners[1] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
            handlePoints[2] = m_rectCorners[2] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
            handlePoints[3] = m_rectCorners[3] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, marginOffset.w * lossyScale.y, 0));

            Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));



            // Draw & process FreeMoveHandles
            
            var capFunction =
#if UNITY_2017_1_OR_NEWER
                (Handles.CapFunction)Handles.DotHandleCap;
#else
                (Handles.DrawCapFunction)Handles.DotCap;
#endif

            // LEFT HANDLE
            Vector3 old_left = (handlePoints[0] + handlePoints[1]) * 0.5f;
            Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, capFunction);
            bool hasChanged = false;
            if (old_left != new_left)
            {
                float delta = old_left.x - new_left.x;
                marginOffset.x += -delta / lossyScale.x;
                //Debug.Log("Left Margin H0:" + handlePoints[0] + "  H1:" + handlePoints[1]);
                hasChanged = true;
            }

            // TOP HANDLE
            Vector3 old_top = (handlePoints[1] + handlePoints[2]) * 0.5f;
            Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, capFunction);
            if (old_top != new_top)
            {
                float delta = old_top.y - new_top.y;
                marginOffset.y += delta / lossyScale.y;
                //Debug.Log("Top Margin H1:" + handlePoints[1] + "  H2:" + handlePoints[2]);   
                hasChanged = true;
            }

            // RIGHT HANDLE
            Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
            Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, capFunction);
            if (old_right != new_right)
            {
                float delta = old_right.x - new_right.x;
                marginOffset.z += delta / lossyScale.x;
                hasChanged = true;
                //Debug.Log("Right Margin H2:" + handlePoints[2] + "  H3:" + handlePoints[3]);
            }

            // BOTTOM HANDLE
            Vector3 old_bottom = (handlePoints[3] + handlePoints[0]) * 0.5f;
            Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, capFunction);
            if (old_bottom != new_bottom)
            {
                float delta = old_bottom.y - new_bottom.y;
                marginOffset.w += -delta / lossyScale.y;
                hasChanged = true;
                //Debug.Log("Bottom Margin H0:" + handlePoints[0] + "  H3:" + handlePoints[3]);
            }

            if (hasChanged)
            {
                Undo.RecordObjects(new Object[] { m_rectTransform, m_textComponent }, "Margin Changes");
                m_textComponent.MarginSizer.SetSize(new Margin(marginOffset));
                m_textComponent.margin = marginOffset;
                EditorUtility.SetDirty(target);
            }
        }


        void DrawPropertySlider(string label, SerializedProperty property)
        {
            float old_LabelWidth = EditorGUIUtility.labelWidth;
            float old_FieldWidth = EditorGUIUtility.fieldWidth;

            Rect rect = EditorGUILayout.GetControlRect(false, 17);

            //EditorGUIUtility.labelWidth = m_labelWidth;

            GUIContent content = label == "" ? GUIContent.none : new GUIContent(label);
            EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);

            EditorGUIUtility.labelWidth = old_LabelWidth;
            EditorGUIUtility.fieldWidth = old_FieldWidth;
        }


        private void DrawDimensionProperty(SerializedProperty property, string label)
        {
            float old_LabelWidth = EditorGUIUtility.labelWidth;
            float old_FieldWidth = EditorGUIUtility.fieldWidth;

            Rect rect = EditorGUILayout.GetControlRect(false, 18);
            Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);

            float width = rect.width + 3;
            pos0.width = old_LabelWidth;
            GUI.Label(pos0, label);

            Rect rectangle = property.rectValue;

            float width_B = width - old_LabelWidth;
            float fieldWidth = width_B / 4;
            pos0.width = fieldWidth - 5;

            pos0.x = old_LabelWidth + 15;
            GUI.Label(pos0, "Width");

            pos0.x += fieldWidth;
            rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);

            pos0.x += fieldWidth;
            GUI.Label(pos0, "Height");

            pos0.x += fieldWidth;
            rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);

            property.rectValue = rectangle;
            EditorGUIUtility.labelWidth = old_LabelWidth;
            EditorGUIUtility.fieldWidth = old_FieldWidth;
        }



        void DrawPropertyBlock(string[] labels, SerializedProperty[] properties)
        {
            float old_LabelWidth = EditorGUIUtility.labelWidth;
            float old_FieldWidth = EditorGUIUtility.fieldWidth;

            Rect rect = EditorGUILayout.GetControlRect(false, 17);
            GUI.Label(new Rect(rect.x, rect.y, old_LabelWidth, rect.height), labels[0]);

            rect.x = old_LabelWidth + 15;
            rect.width = (rect.width + 20 - rect.x) / labels.Length;

            for (int i = 0; i < labels.Length; i++)
            {
                if (i == 0)
                {
                    EditorGUIUtility.labelWidth = 20;
                    EditorGUI.PropertyField(new Rect(rect.x - 20, rect.y, 75, rect.height), properties[i], new GUIContent("  "));
                    rect.x += rect.width;
                }
                else
                {
                    EditorGUIUtility.labelWidth = GUI.skin.textArea.CalcSize(new GUIContent(labels[i])).x;
                    EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 5, rect.height), properties[i], new GUIContent(labels[i]));
                    rect.x += rect.width;
                }

            }

            EditorGUIUtility.labelWidth = old_LabelWidth;
            EditorGUIUtility.fieldWidth = old_FieldWidth;
        }

        void DrawColorGradient(SerializedProperty topLeft, SerializedProperty topRight, SerializedProperty bottomLeft, SerializedProperty bottomRight)
        {
            m_colorMode = (ColorGradientMode)EditorGUILayout.EnumPopup("Color Mode", m_colorMode);
            float w = EditorGUIUtility.labelWidth + 150;
            switch (m_colorMode)
            {
                case ColorGradientMode.Single:
                    Color c = EditorGUILayout.ColorField("Color", topLeft.colorValue, GUILayout.MaxWidth(w));
                    topLeft.colorValue = c;
                    topRight.colorValue = c;
                    bottomLeft.colorValue = c;
                    bottomRight.colorValue = c;
                    break;

                case ColorGradientMode.HorizontalGradient:
                    EditorGUILayout.BeginHorizontal();

                    Color l = EditorGUILayout.ColorField("Color", topLeft.colorValue);
                    Color r = EditorGUILayout.ColorField(" ", bottomRight.colorValue);
                    topLeft.colorValue = l;
                    topRight.colorValue = r;
                    bottomLeft.colorValue = l;
                    bottomRight.colorValue = r;
                    EditorGUILayout.EndHorizontal();
                    break;

                case ColorGradientMode.VerticalGradient:
                    
                    Color t = EditorGUILayout.ColorField("Color", topLeft.colorValue, GUILayout.MaxWidth(w));
                    Color b = EditorGUILayout.ColorField(" ", bottomRight.colorValue, GUILayout.MaxWidth(w));
                    topLeft.colorValue = t;
                    topRight.colorValue = t;
                    bottomLeft.colorValue = b;
                    bottomRight.colorValue = b;
                    break;
                case ColorGradientMode.FourCornersGradient:

                    EditorGUILayout.BeginHorizontal();

                    Color tl = EditorGUILayout.ColorField("Color", topLeft.colorValue);
                    Color tr = EditorGUILayout.ColorField(" ", topRight.colorValue);
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    Color bl = EditorGUILayout.ColorField(" ", bottomLeft.colorValue);
                    Color br = EditorGUILayout.ColorField(" ", bottomRight.colorValue);
                    EditorGUILayout.EndHorizontal();

                    topLeft.colorValue = tl;
                    topRight.colorValue = tr;
                    bottomLeft.colorValue = bl;
                    bottomRight.colorValue = br;
                    break;

                default:
                    break;
            }
        }


        // Method to handle multi object selection
        private bool IsMixSelectionTypes()
        {
            Object[] objects = Selection.gameObjects;
            if (objects.Length > 1)
            {
                //m_isMultiSelection = true;
                for (int i = 0; i < objects.Length; i++)
                {
                    if (((GameObject)objects[i]).GetComponent<TextMeshProUGUI>() == null)
                        return true;
                }
            }
            return false;
        }
    }
}
