Example #1
0
 // Token: 0x06004584 RID: 17796 RVA: 0x001753A4 File Offset: 0x001737A4
 private void LateUpdate()
 {
     if (this.isHoveringObject)
     {
         int num = TMP_TextUtilities.FindIntersectingCharacter(this.m_TextMeshPro, Input.mousePosition, this.m_Camera, true);
         if (num == -1 || num != this.m_lastIndex)
         {
             this.RestoreCachedVertexAttributes(this.m_lastIndex);
             this.m_lastIndex = -1;
         }
         if (num != -1 && num != this.m_lastIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
         {
             this.m_lastIndex = num;
             int       materialReferenceIndex = this.m_TextMeshPro.textInfo.characterInfo[num].materialReferenceIndex;
             int       vertexIndex            = this.m_TextMeshPro.textInfo.characterInfo[num].vertexIndex;
             Vector3[] vertices = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex].vertices;
             Vector2   v        = (vertices[vertexIndex] + vertices[vertexIndex + 2]) / 2f;
             Vector3   b        = v;
             vertices[vertexIndex]    -= b;
             vertices[vertexIndex + 1] = vertices[vertexIndex + 1] - b;
             vertices[vertexIndex + 2] = vertices[vertexIndex + 2] - b;
             vertices[vertexIndex + 3] = vertices[vertexIndex + 3] - b;
             float d = 1.5f;
             this.m_matrix             = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one * d);
             vertices[vertexIndex]     = this.m_matrix.MultiplyPoint3x4(vertices[vertexIndex]);
             vertices[vertexIndex + 1] = this.m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]);
             vertices[vertexIndex + 2] = this.m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]);
             vertices[vertexIndex + 3] = this.m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]);
             vertices[vertexIndex]    += b;
             vertices[vertexIndex + 1] = vertices[vertexIndex + 1] + b;
             vertices[vertexIndex + 2] = vertices[vertexIndex + 2] + b;
             vertices[vertexIndex + 3] = vertices[vertexIndex + 3] + b;
             Color32   color  = new Color32(byte.MaxValue, byte.MaxValue, 192, byte.MaxValue);
             Color32[] colors = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex].colors32;
             colors[vertexIndex]     = color;
             colors[vertexIndex + 1] = color;
             colors[vertexIndex + 2] = color;
             colors[vertexIndex + 3] = color;
             TMP_MeshInfo tmp_MeshInfo = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex];
             int          dst          = vertices.Length - 4;
             tmp_MeshInfo.SwapVertexData(vertexIndex, dst);
             this.m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
         }
         int num2 = TMP_TextUtilities.FindIntersectingWord(this.m_TextMeshPro, Input.mousePosition, this.m_Camera);
         if (this.m_TextPopup_RectTransform != null && this.m_selectedWord != -1 && (num2 == -1 || num2 != this.m_selectedWord))
         {
             TMP_WordInfo tmp_WordInfo = this.m_TextMeshPro.textInfo.wordInfo[this.m_selectedWord];
             for (int i = 0; i < tmp_WordInfo.characterCount; i++)
             {
                 int       num3 = tmp_WordInfo.firstCharacterIndex + i;
                 int       materialReferenceIndex2 = this.m_TextMeshPro.textInfo.characterInfo[num3].materialReferenceIndex;
                 int       vertexIndex2            = this.m_TextMeshPro.textInfo.characterInfo[num3].vertexIndex;
                 Color32[] colors2 = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex2].colors32;
                 Color32   color2  = colors2[vertexIndex2].Tint(1.33333f);
                 colors2[vertexIndex2]     = color2;
                 colors2[vertexIndex2 + 1] = color2;
                 colors2[vertexIndex2 + 2] = color2;
                 colors2[vertexIndex2 + 3] = color2;
             }
             this.m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
             this.m_selectedWord = -1;
         }
         if (num2 != -1 && num2 != this.m_selectedWord && !Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.RightShift))
         {
             this.m_selectedWord = num2;
             TMP_WordInfo tmp_WordInfo2 = this.m_TextMeshPro.textInfo.wordInfo[num2];
             for (int j = 0; j < tmp_WordInfo2.characterCount; j++)
             {
                 int       num4 = tmp_WordInfo2.firstCharacterIndex + j;
                 int       materialReferenceIndex3 = this.m_TextMeshPro.textInfo.characterInfo[num4].materialReferenceIndex;
                 int       vertexIndex3            = this.m_TextMeshPro.textInfo.characterInfo[num4].vertexIndex;
                 Color32[] colors3 = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex3].colors32;
                 Color32   color3  = colors3[vertexIndex3].Tint(0.75f);
                 colors3[vertexIndex3]     = color3;
                 colors3[vertexIndex3 + 1] = color3;
                 colors3[vertexIndex3 + 2] = color3;
                 colors3[vertexIndex3 + 3] = color3;
             }
             this.m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
         }
         int num5 = TMP_TextUtilities.FindIntersectingLink(this.m_TextMeshPro, Input.mousePosition, this.m_Camera);
         if ((num5 == -1 && this.m_selectedLink != -1) || num5 != this.m_selectedLink)
         {
             this.m_TextPopup_RectTransform.gameObject.SetActive(false);
             this.m_selectedLink = -1;
         }
         if (num5 != -1 && num5 != this.m_selectedLink)
         {
             this.m_selectedLink = num5;
             TMP_LinkInfo tmp_LinkInfo = this.m_TextMeshPro.textInfo.linkInfo[num5];
             Vector3      zero         = Vector3.zero;
             RectTransformUtility.ScreenPointToWorldPointInRectangle(this.m_TextMeshPro.rectTransform, Input.mousePosition, this.m_Camera, out zero);
             string linkID = tmp_LinkInfo.GetLinkID();
             if (linkID != null)
             {
                 if (!(linkID == "id_01"))
                 {
                     if (linkID == "id_02")
                     {
                         this.m_TextPopup_RectTransform.position = zero;
                         this.m_TextPopup_RectTransform.gameObject.SetActive(true);
                         this.m_TextPopup_TMPComponent.text = "You have selected link <#ffff00> ID 02";
                     }
                 }
                 else
                 {
                     this.m_TextPopup_RectTransform.position = zero;
                     this.m_TextPopup_RectTransform.gameObject.SetActive(true);
                     this.m_TextPopup_TMPComponent.text = "You have selected link <#ffff00> ID 01";
                 }
             }
         }
     }
     else if (this.m_lastIndex != -1)
     {
         this.RestoreCachedVertexAttributes(this.m_lastIndex);
         this.m_lastIndex = -1;
     }
 }
Example #2
0
        public override void OnInspectorGUI()
        {
            Event current = Event.current;

            base.serializedObject.Update();
            GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", TMP_UIStyleManager.Section_Label);
            GUILayout.Label("Face Info", TMP_UIStyleManager.Section_Label);
            EditorGUI.indentLevel = 1;
            GUI.enabled           = false;
            float labelWidth = EditorGUIUtility.labelWidth = 150f;
            float fieldWidth = EditorGUIUtility.fieldWidth;

            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize"));
            GUI.enabled = true;
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Scale"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("CapHeight"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline"), new GUIContent("Underline Offset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("strikethrough"), new GUIContent("Strikethrough Offset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset"));
            SerializedProperty serializedProperty = m_fontInfo_prop.FindPropertyRelative("SubSize");

            EditorGUILayout.PropertyField(serializedProperty, new GUIContent("Super / Subscript Size"));
            serializedProperty.floatValue = Mathf.Clamp(serializedProperty.floatValue, 0.25f, 1f);
            GUI.enabled           = false;
            EditorGUI.indentLevel = 1;
            GUILayout.Space(18f);
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height"));
            GUI.enabled           = true;
            EditorGUI.indentLevel = 0;
            GUILayout.Space(20f);
            GUILayout.Label("Font Sub-Assets", TMP_UIStyleManager.Section_Label);
            GUI.enabled           = false;
            EditorGUI.indentLevel = 1;
            EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:"));
            EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:"));
            GUI.enabled = true;
            string commandName = Event.current.commandName;

            EditorGUI.indentLevel = 0;
            if (GUILayout.Button("Font Weights\t" + (UI_PanelState.fontWeightPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            {
                UI_PanelState.fontWeightPanel = !UI_PanelState.fontWeightPanel;
            }
            if (UI_PanelState.fontWeightPanel)
            {
                EditorGUIUtility.labelWidth = 120f;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                EditorGUI.indentLevel = 0;
                GUILayout.Label("Select the Font Assets that will be used for the following font weights.", TMP_UIStyleManager.Label);
                GUILayout.Space(10f);
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("<b>Font Weight</b>", TMP_UIStyleManager.Label, GUILayout.Width(117f));
                GUILayout.Label("<b>Normal Style</b>", TMP_UIStyleManager.Label);
                GUILayout.Label("<b>Italic Style</b>", TMP_UIStyleManager.Label);
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular"));
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold"));
                EditorGUILayout.EndVertical();
                EditorGUIUtility.labelWidth = 120f;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                GUILayout.Label("Settings used to simulate a typeface when no font asset is available.", TMP_UIStyleManager.Label);
                GUILayout.Space(5f);
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight"));
                font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3f, 3f);
                if (GUI.changed || commandName == "UndoRedoPerformed")
                {
                    GUI.changed = false;
                    for (int i = 0; i < m_materialPresets.Length; i++)
                    {
                        m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
                    }
                }
                EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight"), GUILayout.MinWidth(100f));
                font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3f, 3f);
                if (GUI.changed || commandName == "UndoRedoPerformed")
                {
                    GUI.changed = false;
                    for (int j = 0; j < m_materialPresets.Length; j++)
                    {
                        m_materialPresets[j].SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
                    }
                }
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Spacing Offset"));
                font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100f, 100f);
                if (GUI.changed || commandName == "UndoRedoPerformed")
                {
                    GUI.changed = false;
                }
                EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing"));
                font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0f, 100f);
                if (GUI.changed || commandName == "UndoRedoPerformed")
                {
                    GUI.changed = false;
                }
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: "));
                font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);
                EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple: "));
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();
            }
            GUILayout.Space(5f);
            EditorGUI.indentLevel = 0;
            if (GUILayout.Button("Fallback Font Assets\t" + (UI_PanelState.fallbackFontAssetPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            {
                UI_PanelState.fallbackFontAssetPanel = !UI_PanelState.fallbackFontAssetPanel;
            }
            if (UI_PanelState.fallbackFontAssetPanel)
            {
                EditorGUIUtility.labelWidth = 120f;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                EditorGUI.indentLevel = 0;
                GUILayout.Label("Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset.", TMP_UIStyleManager.Label);
                GUILayout.Space(10f);
                m_list.DoLayoutList();
                EditorGUILayout.EndVertical();
            }
            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUIUtility.fieldWidth = fieldWidth;
            GUILayout.Space(5f);
            EditorGUI.indentLevel = 0;
            if (GUILayout.Button("Glyph Info\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            {
                UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel;
            }
            if (UI_PanelState.glyphInfoPanel)
            {
                int num2 = m_glyphInfoList_prop.arraySize;
                int num3 = 15;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label, GUILayout.ExpandWidth(true));
                EditorGUILayout.BeginHorizontal();
                EditorGUIUtility.labelWidth = 110f;
                EditorGUI.BeginChangeCheck();
                string text = EditorGUILayout.TextField("Glyph Search", m_searchPattern, "SearchTextField");
                if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
                {
                    if (!string.IsNullOrEmpty(text))
                    {
                        m_searchPattern = text;
                        SearchGlyphTable(m_searchPattern, ref m_searchList);
                    }
                    m_isSearchDirty = false;
                }
                string str = string.IsNullOrEmpty(m_searchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
                if (GUILayout.Button(GUIContent.none, str))
                {
                    GUIUtility.keyboardControl = 0;
                    m_searchPattern            = string.Empty;
                }
                EditorGUILayout.EndHorizontal();
                if (!string.IsNullOrEmpty(m_searchPattern))
                {
                    num2 = m_searchList.Count;
                }
                DisplayGlyphPageNavigation(num2, num3);
                EditorGUILayout.EndVertical();
                if (num2 > 0)
                {
                    for (int k = num3 * m_GlyphPage; k < num2 && k < num3 * (m_GlyphPage + 1); k++)
                    {
                        Rect rect = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
                        int  num4 = k;
                        if (!string.IsNullOrEmpty(m_searchPattern))
                        {
                            num4 = m_searchList[k];
                        }
                        SerializedProperty arrayElementAtIndex = m_glyphInfoList_prop.GetArrayElementAtIndex(num4);
                        EditorGUI.BeginDisabledGroup(k != m_selectedElement);
                        EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);
                        EditorGUILayout.PropertyField(arrayElementAtIndex);
                        EditorGUILayout.EndVertical();
                        EditorGUI.EndDisabledGroup();
                        Rect rect2 = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
                        Rect rect3 = new Rect(rect.x, rect.y, rect2.width, rect2.y - rect.y);
                        if (DoSelectionCheck(rect3))
                        {
                            m_selectedElement           = k;
                            m_AddGlyphWarning.isEnabled = false;
                            m_unicodeHexLabel           = "<i>Unicode Hex ID</i>";
                            GUIUtility.keyboardControl  = 0;
                        }
                        if (m_selectedElement != k)
                        {
                            continue;
                        }
                        TMP_EditorUtility.DrawBox(rect3, 2f, new Color32(40, 192, byte.MaxValue, byte.MaxValue));
                        Rect  controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
                        float num5        = controlRect.width * 0.6f;
                        float num6        = num5 / 3f;
                        Rect  position    = new Rect(controlRect.x + controlRect.width * 0.4f, controlRect.y, num6, controlRect.height);
                        GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID);
                        if (GUI.Button(position, new GUIContent("Copy to")))
                        {
                            GUIUtility.keyboardControl = 0;
                            int dstGlyphID = TMP_TextUtilities.StringToInt(m_dstGlyphID);
                            if (!AddNewGlyph(num4, dstGlyphID))
                            {
                                m_AddGlyphWarning.isEnabled      = true;
                                m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1.0;
                            }
                            m_dstGlyphID    = string.Empty;
                            m_isSearchDirty = true;
                            TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
                        }
                        GUI.enabled = true;
                        position.x += num6;
                        GUI.SetNextControlName("GlyphID_Input");
                        m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID);
                        EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Glyph"), TMP_UIStyleManager.Label);
                        if (GUI.GetNameOfFocusedControl() == "GlyphID_Input")
                        {
                            m_unicodeHexLabel = string.Empty;
                            char character = Event.current.character;
                            if ((character < '0' || character > '9') && (character < 'a' || character > 'f') && (character < 'A' || character > 'F'))
                            {
                                Event.current.character = '\0';
                            }
                        }
                        else
                        {
                            m_unicodeHexLabel = "<i>Unicode Hex ID</i>";
                        }
                        position.x += num6;
                        if (GUI.Button(position, "Remove"))
                        {
                            GUIUtility.keyboardControl = 0;
                            RemoveGlyphFromList(num4);
                            m_selectedElement = -1;
                            m_isSearchDirty   = true;
                            TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
                            return;
                        }
                        if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime)
                        {
                            EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning);
                        }
                    }
                }
                DisplayGlyphPageNavigation(num2, num3);
            }
            GUILayout.Space(5f);
            if (GUILayout.Button("Kerning Table Info\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            {
                UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel;
            }
            if (UI_PanelState.kerningInfoPanel)
            {
                SerializedProperty serializedProperty2 = m_kerningInfo_prop.FindPropertyRelative("kerningPairs");
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Left Char", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label("Right Char", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label("Offset Value", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label(GUIContent.none, GUILayout.Width(20f));
                EditorGUILayout.EndHorizontal();
                GUILayout.BeginVertical(TMP_UIStyleManager.TMP_GUISkin.label);
                int  arraySize = serializedProperty2.arraySize;
                int  num7      = 25;
                Rect rect4;
                if (arraySize > 0)
                {
                    for (int l = num7 * m_KerningPage; l < arraySize && l < num7 * (m_KerningPage + 1); l++)
                    {
                        SerializedProperty arrayElementAtIndex2 = serializedProperty2.GetArrayElementAtIndex(l);
                        rect4 = EditorGUILayout.BeginHorizontal();
                        EditorGUI.PropertyField(new Rect(rect4.x, rect4.y, rect4.width - 20f, rect4.height), arrayElementAtIndex2, GUIContent.none);
                        if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
                        {
                            m_kerningTable.RemoveKerningPair(l);
                            m_fontAsset.ReadFontDefinition();
                            base.serializedObject.Update();
                            isAssetDirty = true;
                            break;
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }
                Rect controlRect2 = EditorGUILayout.GetControlRect(false, 20f);
                controlRect2.width /= 3f;
                int num8 = (!current.shift) ? 1 : 10;
                if (m_KerningPage > 0)
                {
                    GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                }
                if (GUI.Button(controlRect2, "Previous Page"))
                {
                    m_KerningPage -= num8;
                }
                GUI.enabled     = true;
                controlRect2.x += controlRect2.width;
                int num9 = (int)((float)arraySize / (float)num7 + 0.999f);
                GUI.Label(controlRect2, "Page " + (m_KerningPage + 1) + " / " + num9, GUI.skin.button);
                controlRect2.x += controlRect2.width;
                if (num7 * (m_GlyphPage + 1) < arraySize)
                {
                    GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                }
                if (GUI.Button(controlRect2, "Next Page"))
                {
                    m_KerningPage += num8;
                }
                m_KerningPage = Mathf.Clamp(m_KerningPage, 0, arraySize / num7);
                GUILayout.EndVertical();
                GUILayout.Space(10f);
                GUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                rect4 = EditorGUILayout.BeginHorizontal();
                EditorGUI.PropertyField(new Rect(rect4.x, rect4.y, rect4.width - 20f, rect4.height), m_kerningPair_prop);
                GUILayout.Label(GUIContent.none, GUILayout.Height(19f));
                EditorGUILayout.EndHorizontal();
                GUILayout.Space(5f);
                if (GUILayout.Button("Add New Kerning Pair"))
                {
                    int   intValue   = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue;
                    int   intValue2  = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue;
                    float floatValue = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue;
                    errorCode = m_kerningTable.AddKerningPair(intValue, intValue2, floatValue);
                    if (errorCode != -1)
                    {
                        m_kerningTable.SortKerningPairs();
                        m_fontAsset.ReadFontDefinition();
                        base.serializedObject.Update();
                        isAssetDirty = true;
                    }
                    else
                    {
                        timeStamp = DateTime.Now.AddSeconds(5.0);
                    }
                }
                if (errorCode == -1)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.Label);
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                    if (DateTime.Now > timeStamp)
                    {
                        errorCode = 0;
                    }
                }
                GUILayout.EndVertical();
            }
            if (base.serializedObject.ApplyModifiedProperties() || commandName == "UndoRedoPerformed" || isAssetDirty)
            {
                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
                isAssetDirty = false;
                EditorUtility.SetDirty(base.target);
            }
            GUI.enabled = true;
            if (current.type == EventType.MouseDown && current.button == 0)
            {
                m_selectedElement = -1;
            }
        }
Example #3
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //SerializedProperty prop_fileID = property.FindPropertyRelative("fileID");
            SerializedProperty prop_id       = property.FindPropertyRelative("id");
            SerializedProperty prop_name     = property.FindPropertyRelative("name");
            SerializedProperty prop_hashCode = property.FindPropertyRelative("hashCode");
            SerializedProperty prop_x        = property.FindPropertyRelative("x");
            SerializedProperty prop_y        = property.FindPropertyRelative("y");
            SerializedProperty prop_width    = property.FindPropertyRelative("width");
            SerializedProperty prop_height   = property.FindPropertyRelative("height");
            SerializedProperty prop_xOffset  = property.FindPropertyRelative("xOffset");
            SerializedProperty prop_yOffset  = property.FindPropertyRelative("yOffset");
            SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance");
            SerializedProperty prop_scale    = property.FindPropertyRelative("scale");
            //SerializedProperty prop_sprite = property.FindPropertyRelative("sprite");

            // Get a reference to the sprite texture
            Texture tex = (property.serializedObject.targetObject as TMP_SpriteAsset).spriteSheet;

            Vector2 spriteSize = new Vector2(65, 65);

            if (prop_width.floatValue >= prop_height.floatValue)
            {
                spriteSize.y = prop_height.floatValue * spriteSize.x / prop_width.floatValue;
                position.y  += (spriteSize.x - spriteSize.y) / 2;
            }
            else
            {
                spriteSize.x = prop_width.floatValue * spriteSize.y / prop_height.floatValue;
                position.x  += (spriteSize.y - spriteSize.x) / 2;
            }

            // Compute the normalized texture coordinates
            Rect texCoords = new Rect(prop_x.floatValue / tex.width, prop_y.floatValue / tex.height, prop_width.floatValue / tex.width, prop_height.floatValue / tex.height);

            GUI.DrawTextureWithTexCoords(new Rect(position.x + 5, position.y, spriteSize.x, spriteSize.y), tex, texCoords, true);

            // We get Rect since a valid position may not be provided by the caller.
            Rect rect = GUILayoutUtility.GetRect(position.width, 49);

            rect.x += 70;
            rect.y -= 15;

            EditorGUIUtility.labelWidth = 40f;
            EditorGUIUtility.fieldWidth = 45f;

            EditorGUI.BeginChangeCheck();
            EditorGUI.LabelField(new Rect(rect.x + 5f, rect.y, 50f, 18), new GUIContent("ID: " + prop_id.intValue));
            EditorGUI.PropertyField(new Rect(rect.x + 50f, rect.y, rect.width - 125, 18), prop_name, new GUIContent("Name: " + prop_name.stringValue));
            if (EditorGUI.EndChangeCheck())
            {
                // Recompute hashCode for new name
                prop_hashCode.intValue = TMP_TextUtilities.GetSimpleHashCode(prop_name.stringValue);
                // Check to make sure for duplicates
                property.serializedObject.ApplyModifiedProperties();
                // Dictionary needs to be updated since HashCode has changed.
                //TMP_StyleSheet.Instance.LoadStyleDictionary();
            }

            EditorGUIUtility.labelWidth = 30f;
            EditorGUIUtility.fieldWidth = 10f;

            //GUI.enabled = false;
            float width = (rect.width - 75f) / 4;

            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:"));

            //GUI.enabled = true;

            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("OX:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("OY:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("Adv."));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_scale, new GUIContent("SF."));
            if (EditorGUI.EndChangeCheck())
            {
                //Sprite sprite = prop_sprite.objectReferenceValue as Sprite;
                //sprite = Sprite.Create(sprite.texture, sprite.rect, new Vector2(0.1f, 0.8f));
                //prop_sprite.objectReferenceValue = sprite;
                //Debug.Log(sprite.bounds);
            }
        }
        public override void OnInspectorGUI()
        {
            // Check Warnings


            //Debug.Log("OnInspectorGUI Called.");
            Event currentEvent = Event.current;

            serializedObject.Update();

            GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", TMP_UIStyleManager.Section_Label);

            // TextMeshPro Font Info Panel
            GUILayout.Label("Face Info", TMP_UIStyleManager.Section_Label);
            EditorGUI.indentLevel = 1;

            GUI.enabled = false; // Lock UI

            float labelWidth = EditorGUIUtility.labelWidth = 150f;
            float fieldWidth = EditorGUIUtility.fieldWidth;

            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize"));

            GUI.enabled = true;
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Scale"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight"));

            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("CapHeight"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline"));
            //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("UnderlineThickness"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset"));
            
            SerializedProperty subSize_prop = m_fontInfo_prop.FindPropertyRelative("SubSize");
            EditorGUILayout.PropertyField(subSize_prop, new GUIContent("Super / Subscript Size"));
            subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f);
            

            GUI.enabled = false;
            //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));

            //GUILayout.Label("Atlas Size");
            EditorGUI.indentLevel = 1;
            GUILayout.Space(18);
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height"));

            GUI.enabled = true;
            EditorGUI.indentLevel = 0;
            GUILayout.Space(20);
            GUILayout.Label("Font Sub-Assets", TMP_UIStyleManager.Section_Label);
                  
            GUI.enabled = false;
            EditorGUI.indentLevel = 1;
            EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:"));
            EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:"));

            GUI.enabled = true;

            string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events

            // FONT SETTINGS
            EditorGUI.indentLevel = 0;
            if (GUILayout.Button("Font Weights\t" + (UI_PanelState.fontWeightPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
                UI_PanelState.fontWeightPanel = !UI_PanelState.fontWeightPanel;


            if (UI_PanelState.fontWeightPanel)
            {
                EditorGUIUtility.labelWidth = 120;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                EditorGUI.indentLevel = 0;
                GUILayout.Label("Select the Font Assets that will be used for the following font weights.", TMP_UIStyleManager.Label);
                GUILayout.Space(10f);
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("<b>Font Weight</b>", TMP_UIStyleManager.Label, GUILayout.Width(117));
                GUILayout.Label("<b>Normal Style</b>", TMP_UIStyleManager.Label);
                GUILayout.Label("<b>Italic Style</b>", TMP_UIStyleManager.Label);
                EditorGUILayout.EndHorizontal();

                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(1), new GUIContent("100 - Thin"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(2), new GUIContent("200 - Extra-Light"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(3), new GUIContent("300 - Light"));
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(5), new GUIContent("500 - Medium"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(6), new GUIContent("600 - Demi-Bold"));
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(8), new GUIContent("800 - Heavy"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(9), new GUIContent("900 - Black"));

                EditorGUILayout.EndVertical();

                //EditorGUI.indentLevel = 1;
                EditorGUIUtility.labelWidth = 120f;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                GUILayout.Label("Settings used to simulate a typeface when no font asset is available.", TMP_UIStyleManager.Label);
                GUILayout.Space(5f);
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight"));
                font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;

                    // Modify the material property on matching material presets.
                    for (int i = 0; i < m_materialPresets.Length; i++)
                        m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
                }


                EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight"), GUILayout.MinWidth(100));
                font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;

                    // Modify the material property on matching material presets.
                    for (int i = 0; i < m_materialPresets.Length; i++)
                        m_materialPresets[i].SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Spacing Offset"));
                font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100, 100);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;
                }

                EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing"));
                font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: "));
                font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);

                EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple: "));

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();
            }

            GUILayout.Space(5);

            // FALLBACK FONT ASSETS
            EditorGUI.indentLevel = 0;
            if (GUILayout.Button("Fallback Font Assets\t" + (UI_PanelState.fallbackFontAssetPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
                UI_PanelState.fallbackFontAssetPanel = !UI_PanelState.fallbackFontAssetPanel;


            if (UI_PanelState.fallbackFontAssetPanel)
            {
                EditorGUIUtility.labelWidth = 120;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
                EditorGUI.indentLevel = 0;
                GUILayout.Label("Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset.", TMP_UIStyleManager.Label);
                GUILayout.Space(10f);

                m_list.DoLayoutList();

                EditorGUILayout.EndVertical();
            }


            // GLYPH INFO TABLE
            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUIUtility.fieldWidth = fieldWidth;
            GUILayout.Space(5);
            EditorGUI.indentLevel = 0;

            if (GUILayout.Button("Glyph Info\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
                UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel;


            if (UI_PanelState.glyphInfoPanel)
            {
                int arraySize = m_glyphInfoList_prop.arraySize;
                int itemsPerPage = 15;

                // Display Glyph Management Tools
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label, GUILayout.ExpandWidth(true));
                {
                    // Search Bar implementation
                    #region DISPLAY SEARCH BAR
                    EditorGUILayout.BeginHorizontal();
                    {
                        EditorGUIUtility.labelWidth = 110f;
                        EditorGUI.BeginChangeCheck();
                        string searchPattern = EditorGUILayout.TextField("Glyph Search", m_searchPattern, "SearchTextField");
                        if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
                        {
                            if (string.IsNullOrEmpty(searchPattern) == false)
                            {
                                //GUIUtility.keyboardControl = 0;
                                m_searchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
                                
                                // Search Glyph Table for potential matches
                                SearchGlyphTable(m_searchPattern, ref m_searchList);
                            }

                            m_isSearchDirty = false;
                        }

                        string styleName = string.IsNullOrEmpty(m_searchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
                        if (GUILayout.Button(GUIContent.none, styleName))
                        {
                            GUIUtility.keyboardControl = 0;
                            m_searchPattern = string.Empty;
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                    #endregion

                    // Display Page Navigation
                    if (!string.IsNullOrEmpty(m_searchPattern))
                        arraySize = m_searchList.Count;

                    DisplayGlyphPageNavigation(arraySize, itemsPerPage);
                }
                EditorGUILayout.EndVertical();

                // Display Glyph Table Elements
                #region Glyph Table
                if (arraySize > 0)
                {
                    // Display each GlyphInfo entry using the GlyphInfo property drawer.
                    for (int i = itemsPerPage * m_GlyphPage; i < arraySize && i < itemsPerPage * (m_GlyphPage + 1); i++)
                    {
                        // Define the start of the selection region of the element.
                        Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        int elementIndex = i;
                        if (!string.IsNullOrEmpty(m_searchPattern))
                            elementIndex = m_searchList[i];
                            
                        SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(elementIndex);

                        EditorGUI.BeginDisabledGroup(i != m_selectedElement);
                        {
                            EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);

                            EditorGUILayout.PropertyField(glyphInfo);

                            EditorGUILayout.EndVertical();
                        }
                        EditorGUI.EndDisabledGroup();

                        // Define the end of the selection region of the element.
                        Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        // Check for Item selection
                        Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
                        if (DoSelectionCheck(selectionArea))
                        {
                            m_selectedElement = i;
                            m_AddGlyphWarning.isEnabled = false;
                            m_unicodeHexLabel = k_placeholderUnicodeHex;
                            GUIUtility.keyboardControl = 0;
                        }


                        // Draw Selection Highlight and Glyph Options
                        if (m_selectedElement == i)
                        {
                            TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));

                            // Draw Glyph management options
                            Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
                            float optionAreaWidth = controlRect.width * 0.6f;
                            float btnWidth = optionAreaWidth / 3;

                            Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height);

                            // Copy Selected Glyph to Target Glyph ID
                            GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID);
                            if (GUI.Button(position, new GUIContent("Copy to")))
                            {
                                GUIUtility.keyboardControl = 0;

                                // Convert Hex Value to Decimal
                                int dstGlyphID = TMP_TextUtilities.StringToInt(m_dstGlyphID);

                                //Add new glyph at target Unicode hex id.
                                if (!AddNewGlyph(elementIndex, dstGlyphID))
                                {
                                    m_AddGlyphWarning.isEnabled = true;
                                    m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1;
                                }

                                m_dstGlyphID = string.Empty;
                                m_isSearchDirty = true;

                                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
                            }

                            // Target Glyph ID
                            GUI.enabled = true;
                            position.x += btnWidth;

                            GUI.SetNextControlName("GlyphID_Input");
                            m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID);

                            // Placeholder text
                            EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Glyph"), TMP_UIStyleManager.Label);

                            // Only filter the input when the destination glyph ID text field has focus.
                            if (GUI.GetNameOfFocusedControl() == "GlyphID_Input")
                            {
                                m_unicodeHexLabel = string.Empty;

                                //Filter out unwanted characters.
                                char chr = Event.current.character;
                                if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                                {
                                    Event.current.character = '\0';
                                }
                            }
                            else
                                m_unicodeHexLabel = k_placeholderUnicodeHex;


                            // Remove Glyph
                            position.x += btnWidth;
                            if (GUI.Button(position, "Remove"))
                            {
                                GUIUtility.keyboardControl = 0;

                                RemoveGlyphFromList(elementIndex);

                                m_selectedElement = -1;
                                m_isSearchDirty = true;

                                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);

                                return;
                            }

                            if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime)
                            {
                                EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning);
                            }

                        }
                    }
                }

                DisplayGlyphPageNavigation(arraySize, itemsPerPage);
            }
            #endregion


            // KERNING TABLE PANEL
            #region Kerning Table
            GUILayout.Space(5);
            if (GUILayout.Button("Kerning Table Info\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
                UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel;


            if (UI_PanelState.kerningInfoPanel)
            {
                
                Rect pos;

                SerializedProperty kerningPairs_prop = m_kerningInfo_prop.FindPropertyRelative("kerningPairs");

                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Left Char", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label("Right Char", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label("Offset Value", TMP_UIStyleManager.TMP_GUISkin.label);
                GUILayout.Label(GUIContent.none, GUILayout.Width(20));
                EditorGUILayout.EndHorizontal();

                GUILayout.BeginVertical(TMP_UIStyleManager.TMP_GUISkin.label);

                int arraySize = kerningPairs_prop.arraySize;
                int itemsPerPage = 25;

                if (arraySize > 0)
                {
                    // Display each GlyphInfo entry using the GlyphInfo property drawer.
                    for (int i = itemsPerPage * m_KerningPage; i < arraySize && i < itemsPerPage * (m_KerningPage + 1); i++)
                    {
                        SerializedProperty kerningPair_prop = kerningPairs_prop.GetArrayElementAtIndex(i);

                        pos = EditorGUILayout.BeginHorizontal();

                        EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), kerningPair_prop, GUIContent.none);

                        // Button to Delete Kerning Pair
                        if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
                        {
                            m_kerningTable.RemoveKerningPair(i);
                            m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
                            serializedObject.Update(); // Get an updated version of the SerializedObject.
                            isAssetDirty = true;
                            break;
                        }

                        EditorGUILayout.EndHorizontal();
                    }
                }

                Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
                pagePos.width /= 3;

                int shiftMultiplier = currentEvent.shift ? 10 : 1;

                // Previous Page
                if (m_KerningPage > 0) GUI.enabled = true;
                else GUI.enabled = false;

                if (GUI.Button(pagePos, "Previous Page"))
                    m_KerningPage -= 1 * shiftMultiplier;

                // Page Counter
                GUI.enabled = true;
                pagePos.x += pagePos.width;
                int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
                GUI.Label(pagePos, "Page " + (m_KerningPage + 1) + " / " + totalPages, GUI.skin.button);

                // Next Page
                pagePos.x += pagePos.width;
                if (itemsPerPage * (m_GlyphPage + 1) < arraySize) GUI.enabled = true;
                else GUI.enabled = false;

                if (GUI.Button(pagePos, "Next Page"))
                    m_KerningPage += 1 * shiftMultiplier;

                m_KerningPage = Mathf.Clamp(m_KerningPage, 0, arraySize / itemsPerPage);

                GUILayout.EndVertical();

                GUILayout.Space(10);


                // Add New Kerning Pair Section
                GUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);

                pos = EditorGUILayout.BeginHorizontal();

                // Draw Empty Kerning Pair 
                EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), m_kerningPair_prop);
                GUILayout.Label(GUIContent.none, GUILayout.Height(19));

                EditorGUILayout.EndHorizontal();

                GUILayout.Space(5);

                if (GUILayout.Button("Add New Kerning Pair"))
                {
                    int asci_left = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue;
                    int asci_right = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue;
                    float xOffset = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue;

                    errorCode = m_kerningTable.AddKerningPair(asci_left, asci_right, xOffset);

                    // Sort Kerning Pairs & Reload Font Asset if new kerning pair was added.
                    if (errorCode != -1)
                    {
                        m_kerningTable.SortKerningPairs();
                        m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
                        serializedObject.Update(); // Get an updated version of the SerializedObject.
                        isAssetDirty = true;
                    }
                    else
                    {
                        timeStamp = System.DateTime.Now.AddSeconds(5);
                    }
                }

                if (errorCode == -1)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.Label);
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();

                    if (System.DateTime.Now > timeStamp)
                        errorCode = 0;
                }

                GUILayout.EndVertical();
            }
            #endregion


            if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
            {
                //Debug.Log("Serialized properties have changed.");
                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);

                isAssetDirty = false;
                EditorUtility.SetDirty(target);
                //TMPro_EditorUtility.RepaintAll(); // Consider SetDirty
            }


            // Clear selection if mouse event was not consumed. 
            GUI.enabled = true;
           // if (currentEvent.type == EventType.mouseDown && currentEvent.button == 0)
			if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
				
                m_selectedElement = -1;
Example #5
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)

        {
            SerializedProperty nameProperty = property.FindPropertyRelative("m_Name");

            SerializedProperty hashCodeProperty = property.FindPropertyRelative("m_HashCode");

            SerializedProperty openingDefinitionProperty = property.FindPropertyRelative("m_OpeningDefinition");

            SerializedProperty closingDefinitionProperty = property.FindPropertyRelative("m_ClosingDefinition");

            SerializedProperty openingDefinitionArray = property.FindPropertyRelative("m_OpeningTagArray");

            SerializedProperty closingDefinitionArray = property.FindPropertyRelative("m_ClosingTagArray");



            EditorGUIUtility.labelWidth = 90;

            position.height = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;

            float labelHeight = position.height + 2f;



            EditorGUI.BeginChangeCheck();

            Rect rect0 = new Rect(position.x, position.y, (position.width) / 2 + 5, position.height);

            EditorGUI.PropertyField(rect0, nameProperty);

            if (EditorGUI.EndChangeCheck())

            {
                // Recompute HashCode if name has changed.

                hashCodeProperty.intValue = TMP_TextUtilities.GetSimpleHashCode(nameProperty.stringValue);



                property.serializedObject.ApplyModifiedProperties();

                // Dictionary needs to be updated since HashCode has changed.

                TMP_StyleSheet.RefreshStyles();
            }



            // HashCode

            Rect rect1 = new Rect(rect0.x + rect0.width + 5, position.y, 65, position.height);

            GUI.Label(rect1, "HashCode");

            GUI.enabled = false;

            rect1.x += 65;

            rect1.width = position.width / 2 - 75;

            EditorGUI.PropertyField(rect1, hashCodeProperty, GUIContent.none);



            GUI.enabled = true;



            // Text Tags

            EditorGUI.BeginChangeCheck();



            // Opening Tags

            position.y += labelHeight;

            GUI.Label(position, "Opening Tags");

            Rect textRect1 = new Rect(108, position.y, position.width - 86, 35);

            openingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect1, openingDefinitionProperty.stringValue);

            if (EditorGUI.EndChangeCheck())

            {
                // If any properties have changed, we need to update the Opening and Closing Arrays.

                int size = openingDefinitionProperty.stringValue.Length;



                // Adjust array size to match new string length.

                if (openingDefinitionArray.arraySize != size)
                {
                    openingDefinitionArray.arraySize = size;
                }



                for (int i = 0; i < size; i++)

                {
                    SerializedProperty element = openingDefinitionArray.GetArrayElementAtIndex(i);

                    element.intValue = openingDefinitionProperty.stringValue[i];
                }
            }



            EditorGUI.BeginChangeCheck();



            // Closing Tags

            position.y += 38;

            GUI.Label(position, "Closing Tags");

            Rect textRect2 = new Rect(108, position.y, position.width - 86, 35);

            closingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect2, closingDefinitionProperty.stringValue);



            if (EditorGUI.EndChangeCheck())

            {
                // If any properties have changed, we need to update the Opening and Closing Arrays.

                int size = closingDefinitionProperty.stringValue.Length;



                // Adjust array size to match new string length.

                if (closingDefinitionArray.arraySize != size)
                {
                    closingDefinitionArray.arraySize = size;
                }



                for (int i = 0; i < size; i++)

                {
                    SerializedProperty element = closingDefinitionArray.GetArrayElementAtIndex(i);

                    element.intValue = closingDefinitionProperty.stringValue[i];
                }
            }
        }
 private void LateUpdate()
 {
     this.m_isHoveringObject = false;
     if (TMP_TextUtilities.IsIntersectingRectTransform(this.m_TextMeshPro.rectTransform, Input.mousePosition, Camera.main))
     {
         this.m_isHoveringObject = true;
     }
     if (this.m_isHoveringObject)
     {
         int num = TMP_TextUtilities.FindIntersectingCharacter(this.m_TextMeshPro, Input.mousePosition, Camera.main, true);
         if (num != -1 && num != this.m_lastCharIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
         {
             this.m_lastCharIndex = num;
             int       materialReferenceIndex = this.m_TextMeshPro.textInfo.characterInfo[num].materialReferenceIndex;
             int       vertexIndex            = this.m_TextMeshPro.textInfo.characterInfo[num].vertexIndex;
             Color32   color  = new Color32((byte)UnityEngine.Random.Range(0, 255), (byte)UnityEngine.Random.Range(0, 255), (byte)UnityEngine.Random.Range(0, 255), byte.MaxValue);
             Color32[] colors = this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex].colors32;
             colors[vertexIndex]     = color;
             colors[vertexIndex + 1] = color;
             colors[vertexIndex + 2] = color;
             colors[vertexIndex + 3] = color;
             this.m_TextMeshPro.textInfo.meshInfo[materialReferenceIndex].mesh.colors32 = colors;
         }
         int num2 = TMP_TextUtilities.FindIntersectingLink(this.m_TextMeshPro, Input.mousePosition, this.m_Camera);
         if ((num2 == -1 && this.m_selectedLink != -1) || num2 != this.m_selectedLink)
         {
             this.m_selectedLink = -1;
         }
         if (num2 != -1 && num2 != this.m_selectedLink)
         {
             this.m_selectedLink = num2;
             TMP_LinkInfo tmp_LinkInfo = this.m_TextMeshPro.textInfo.linkInfo[num2];
             Debug.Log(string.Concat(new string[]
             {
                 "Link ID: \"",
                 tmp_LinkInfo.GetLinkID(),
                 "\"   Link Text: \"",
                 tmp_LinkInfo.GetLinkText(),
                 "\""
             }));
             Vector3 zero = Vector3.zero;
             RectTransformUtility.ScreenPointToWorldPointInRectangle(this.m_TextMeshPro.rectTransform, Input.mousePosition, this.m_Camera, out zero);
             string linkID = tmp_LinkInfo.GetLinkID();
             if (linkID != null)
             {
                 if (!(linkID == "id_01"))
                 {
                     if (!(linkID == "id_02"))
                     {
                     }
                 }
             }
         }
         int num3 = TMP_TextUtilities.FindIntersectingWord(this.m_TextMeshPro, Input.mousePosition, Camera.main);
         if (num3 != -1 && num3 != this.m_lastWordIndex)
         {
             this.m_lastWordIndex = num3;
             TMP_WordInfo tmp_WordInfo = this.m_TextMeshPro.textInfo.wordInfo[num3];
             Vector3      position     = this.m_TextMeshPro.transform.TransformPoint(this.m_TextMeshPro.textInfo.characterInfo[tmp_WordInfo.firstCharacterIndex].bottomLeft);
             position = Camera.main.WorldToScreenPoint(position);
             Color32[] colors2 = this.m_TextMeshPro.textInfo.meshInfo[0].colors32;
             Color32   color2  = new Color32((byte)UnityEngine.Random.Range(0, 255), (byte)UnityEngine.Random.Range(0, 255), (byte)UnityEngine.Random.Range(0, 255), byte.MaxValue);
             for (int i = 0; i < tmp_WordInfo.characterCount; i++)
             {
                 int vertexIndex2 = this.m_TextMeshPro.textInfo.characterInfo[tmp_WordInfo.firstCharacterIndex + i].vertexIndex;
                 colors2[vertexIndex2]     = color2;
                 colors2[vertexIndex2 + 1] = color2;
                 colors2[vertexIndex2 + 2] = color2;
                 colors2[vertexIndex2 + 3] = color2;
             }
             this.m_TextMeshPro.mesh.colors32 = colors2;
         }
     }
 }
Example #7
0
        // Update existing SpriteInfo
        private static List <TMP_Sprite> UpdateSpriteInfo(TMP_SpriteAsset spriteAsset)
        {
            //Debug.Log("Updating Sprite Asset.");

            string filePath = AssetDatabase.GetAssetPath(spriteAsset.spriteSheet);

            // Get all the Sprites sorted Left to Right / Top to Bottom
            Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray();

            for (int i = 0; i < sprites.Length; i++)
            {
                Sprite sprite = sprites[i];

                // Check if sprite already exists in the SpriteInfoList
                int index = -1;

                if (spriteAsset.spriteInfoList[i].sprite != null)
                {
                    index = spriteAsset.spriteInfoList.FindIndex(item => item.sprite.GetInstanceID() == sprite.GetInstanceID());
                }

                // Use existing SpriteInfo if it already exists
                TMP_Sprite spriteInfo = index == -1 ? new TMP_Sprite() : spriteAsset.spriteInfoList[index];

                Rect spriteRect = sprite.rect;
                if (spriteInfo.name != sprite.name)
                {
                    // Preserve the existing sprite name.
                    sprite.name = spriteInfo.name;
                    //spriteInfo.name = sprite.name;
                    spriteInfo.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteInfo.name);
                }

                spriteInfo.x      = spriteRect.x;
                spriteInfo.y      = spriteRect.y;
                spriteInfo.width  = spriteRect.width;
                spriteInfo.height = spriteRect.height;

                // Get Sprite Pivot
                Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2));

                // The position of the pivot influences the Offset position.
                spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height);

                if (index == -1)
                {
                    // Find the next available index for this Sprite
                    int[] ids = spriteAsset.spriteInfoList.Select(item => item.id).ToArray();

                    int id = 0;
                    for (int j = 0; j < ids.Length; j++)
                    {
                        if (ids[0] != 0)
                        {
                            break;
                        }

                        if (j > 0 && (ids[j] - ids[j - 1]) > 1)
                        {
                            id = ids[j - 1] + 1;
                            break;
                        }

                        id = j + 1;
                    }

                    //spriteInfo.fileID = fileID;
                    spriteInfo.id       = id;
                    spriteInfo.xAdvance = spriteRect.width;
                    spriteInfo.scale    = 1.0f;

                    spriteInfo.xOffset = spriteInfo.pivot.x;
                    spriteInfo.yOffset = spriteInfo.pivot.y;

                    spriteAsset.spriteInfoList.Add(spriteInfo);
                }
                else
                {
                    spriteAsset.spriteInfoList[index] = spriteInfo;
                }
            }

            return(spriteAsset.spriteInfoList);
        }
Example #8
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty property2           = property.FindPropertyRelative("id");
            SerializedProperty serializedProperty  = property.FindPropertyRelative("name");
            SerializedProperty serializedProperty2 = property.FindPropertyRelative("hashCode");
            SerializedProperty serializedProperty3 = property.FindPropertyRelative("unicode");
            SerializedProperty serializedProperty4 = property.FindPropertyRelative("x");
            SerializedProperty serializedProperty5 = property.FindPropertyRelative("y");
            SerializedProperty serializedProperty6 = property.FindPropertyRelative("width");
            SerializedProperty serializedProperty7 = property.FindPropertyRelative("height");
            SerializedProperty property3           = property.FindPropertyRelative("xOffset");
            SerializedProperty property4           = property.FindPropertyRelative("yOffset");
            SerializedProperty property5           = property.FindPropertyRelative("xAdvance");
            SerializedProperty property6           = property.FindPropertyRelative("scale");
            SerializedProperty serializedProperty8 = property.FindPropertyRelative("sprite");
            Texture            spriteSheet         = (property.serializedObject.targetObject as TMP_SpriteAsset).spriteSheet;

            if (spriteSheet == null)
            {
                Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + property.serializedObject.targetObject.name + "] Sprite Asset.", property.serializedObject.targetObject);
                return;
            }
            Vector2 vector = new Vector2(65f, 65f);

            if (serializedProperty6.floatValue >= serializedProperty7.floatValue)
            {
                vector.y    = serializedProperty7.floatValue * vector.x / serializedProperty6.floatValue;
                position.y += (vector.x - vector.y) / 2f;
            }
            else
            {
                vector.x    = serializedProperty6.floatValue * vector.y / serializedProperty7.floatValue;
                position.x += (vector.y - vector.x) / 2f;
            }
            GUI.DrawTextureWithTexCoords(texCoords: new Rect(serializedProperty4.floatValue / (float)spriteSheet.width, serializedProperty5.floatValue / (float)spriteSheet.height, serializedProperty6.floatValue / (float)spriteSheet.width, serializedProperty7.floatValue / (float)spriteSheet.height), position: new Rect(position.x + 5f, position.y, vector.x, vector.y), image: spriteSheet, alphaBlend: true);
            Rect rect = new Rect(position.x, position.y, position.width, 49f);

            rect.x += 70f;
            bool enabled = GUI.enabled;

            GUI.enabled = false;
            EditorGUIUtility.labelWidth = 30f;
            EditorGUI.PropertyField(new Rect(rect.x + 5f, rect.y, 65f, 18f), property2, new GUIContent("ID:"));
            GUI.enabled = enabled;
            EditorGUI.BeginChangeCheck();
            EditorGUIUtility.labelWidth = 55f;
            GUI.SetNextControlName("Unicode Input");
            string s = EditorGUI.TextField(new Rect(rect.x + 75f, rect.y, 105f, 18f), "Unicode:", serializedProperty3.intValue.ToString("X"));

            if (GUI.GetNameOfFocusedControl() == "Unicode Input")
            {
                char character = Event.current.character;
                if ((character < '0' || character > '9') && (character < 'a' || character > 'f') && (character < 'A' || character > 'F'))
                {
                    Event.current.character = '\0';
                }
                if (EditorGUI.EndChangeCheck())
                {
                    serializedProperty3.intValue = TMP_TextUtilities.StringToInt(s);
                    property.serializedObject.ApplyModifiedProperties();
                    TMP_SpriteAsset tMP_SpriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset;
                    tMP_SpriteAsset.UpdateLookupTables();
                }
            }
            EditorGUIUtility.labelWidth = 45f;
            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(new Rect(rect.x + 185f, rect.y, rect.width - 260f, 18f), serializedProperty, new GUIContent("Name: " + serializedProperty.stringValue));
            if (EditorGUI.EndChangeCheck())
            {
                Sprite sprite = serializedProperty8.objectReferenceValue as Sprite;
                if (sprite != null)
                {
                    sprite.name = serializedProperty.stringValue;
                }
                serializedProperty2.intValue = TMP_TextUtilities.GetSimpleHashCode(serializedProperty.stringValue);
                property.serializedObject.ApplyModifiedProperties();
            }
            EditorGUIUtility.labelWidth = 30f;
            EditorGUIUtility.fieldWidth = 10f;
            float num = (rect.width - 75f) / 4f;

            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 0f, rect.y + 22f, num - 5f, 18f), serializedProperty4, new GUIContent("X:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 1f, rect.y + 22f, num - 5f, 18f), serializedProperty5, new GUIContent("Y:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 2f, rect.y + 22f, num - 5f, 18f), serializedProperty6, new GUIContent("W:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 3f, rect.y + 22f, num - 5f, 18f), serializedProperty7, new GUIContent("H:"));
            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 0f, rect.y + 44f, num - 5f, 18f), property3, new GUIContent("OX:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 1f, rect.y + 44f, num - 5f, 18f), property4, new GUIContent("OY:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 2f, rect.y + 44f, num - 5f, 18f), property5, new GUIContent("Adv."));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + num * 3f, rect.y + 44f, num - 5f, 18f), property6, new GUIContent("SF."));
            if (!EditorGUI.EndChangeCheck())
            {
            }
        }
Example #9
0
        void LateUpdate()
        {
            if (TMP_TextUtilities.IsIntersectingRectTransform(m_TextComponent.rectTransform, Input.mousePosition, m_Camera))
            {
                #region Example of Character or Sprite Selection
                int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextComponent, Input.mousePosition, m_Camera, true);
                if (charIndex != -1 && charIndex != m_lastCharIndex)
                {
                    m_lastCharIndex = charIndex;

                    TMP_TextElementType elementType = m_TextComponent.textInfo.characterInfo[charIndex].elementType;

                    // Send event to any event listeners depending on whether it is a character or sprite.
                    if (elementType == TMP_TextElementType.Character)
                    {
                        SendOnCharacterSelection(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
                    }
                    else if (elementType == TMP_TextElementType.Sprite)
                    {
                        SendOnSpriteSelection(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
                    }
                }
                #endregion


                #region Example of Word Selection
                // Check if Mouse intersects any words and if so assign a random color to that word.
                int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, Input.mousePosition, m_Camera);
                if (wordIndex != -1 && wordIndex != m_lastWordIndex)
                {
                    m_lastWordIndex = wordIndex;

                    // Get the information about the selected word.
                    TMP_WordInfo wInfo = m_TextComponent.textInfo.wordInfo[wordIndex];

                    // Send the event to any listeners.
                    SendOnWordSelection(wInfo.GetWord(), wInfo.firstCharacterIndex, wInfo.characterCount);
                }
                #endregion


                #region Example of Line Selection
                // Check if Mouse intersects any words and if so assign a random color to that word.
                int lineIndex = TMP_TextUtilities.FindIntersectingLine(m_TextComponent, Input.mousePosition, m_Camera);
                if (lineIndex != -1 && lineIndex != m_lastLineIndex)
                {
                    m_lastLineIndex = lineIndex;

                    // Get the information about the selected word.
                    TMP_LineInfo lineInfo = m_TextComponent.textInfo.lineInfo[lineIndex];

                    // Send the event to any listeners.
                    char[] buffer = new char[lineInfo.characterCount];
                    for (int i = 0; i < lineInfo.characterCount && i < m_TextComponent.textInfo.characterInfo.Length; i++)
                    {
                        buffer[i] = m_TextComponent.textInfo.characterInfo[i + lineInfo.firstCharacterIndex].character;
                    }

                    string lineText = new string(buffer);
                    SendOnLineSelection(lineText, lineInfo.firstCharacterIndex, lineInfo.characterCount);
                }
                #endregion


                #region Example of Link Handling
                // Check if mouse intersects with any links.
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextComponent, Input.mousePosition, m_Camera);

                // Handle new Link selection.
                if (linkIndex != -1 && linkIndex != m_selectedLink)
                {
                    m_selectedLink = linkIndex;

                    // Get information about the link.
                    TMP_LinkInfo linkInfo = m_TextComponent.textInfo.linkInfo[linkIndex];

                    // Send the event to any listeners.
                    SendOnLinkSelection(linkInfo.GetLinkID(), linkInfo.GetLinkText(), linkIndex);
                }
                #endregion
            }
        }
        public static void CreateSpriteAsset()
        {
            Object target = Selection.activeObject;

            // Make sure the selection is a texture.
            if (target == null || target.GetType() != typeof(Texture2D))
            {
                Debug.LogWarning("A texture which contains sprites must first be selected in order to create a TextMesh Pro Sprite Asset.");
                return;
            }

            Texture2D sourceTex = target as Texture2D;

            // Get the path to the selected texture.
            string filePathWithName         = AssetDatabase.GetAssetPath(sourceTex);
            string fileNameWithExtension    = Path.GetFileName(filePathWithName);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
            string filePath = filePathWithName.Replace(fileNameWithExtension, "");

            // Check if Sprite Asset already exists
            TMP_SpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(filePath + fileNameWithoutExtension + ".asset", typeof(TMP_SpriteAsset)) as TMP_SpriteAsset;
            bool            isNewAsset  = spriteAsset == null ? true : false;

            if (isNewAsset)
            {
                // Create new Sprite Asset using this texture
                spriteAsset = ScriptableObject.CreateInstance <TMP_SpriteAsset>();
                AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset");

                spriteAsset.version = "1.1.0";

                // Compute the hash code for the sprite asset.
                spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name);

                // Assign new Sprite Sheet texture to the Sprite Asset.
                spriteAsset.spriteSheet = sourceTex;

                List <TMP_SpriteGlyph>     spriteGlyphTable     = new List <TMP_SpriteGlyph>();
                List <TMP_SpriteCharacter> spriteCharacterTable = new List <TMP_SpriteCharacter>();

                PopulateSpriteTables(sourceTex, ref spriteCharacterTable, ref spriteGlyphTable);

                spriteAsset.spriteCharacterTable = spriteCharacterTable;
                spriteAsset.spriteGlyphTable     = spriteGlyphTable;

                // Add new default material for sprite asset.
                AddDefaultMaterial(spriteAsset);
            }
            //else
            //{
            //    spriteAsset.spriteInfoList = UpdateSpriteInfo(spriteAsset);

            //    // Make sure the sprite asset already contains a default material
            //    if (spriteAsset.material == null)
            //    {
            //        // Add new default material for sprite asset.
            //        AddDefaultMaterial(spriteAsset);
            //    }

            //}

            // Update Lookup tables.
            spriteAsset.UpdateLookupTables();

            // Get the Sprites contained in the Sprite Sheet
            EditorUtility.SetDirty(spriteAsset);

            //spriteAsset.sprites = sprites;

            // Set source texture back to Not Readable.
            //texImporter.isReadable = false;


            AssetDatabase.SaveAssets();

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset));  // Re-import font asset to get the new updated version.

            //AssetDatabase.Refresh();
        }
Example #11
0
    public bool TestForHit(Vector2 screenPoint, Camera eventCamera, Action <string, int> block)
    {
        TMP_TextInfo textInfo = null;
        TMP_Text     text     = null;

        if (entity.text != null)
        {
            text     = entity.text;
            textInfo = entity.text.textInfo;
        }
        if (entity.textGUI != null)
        {
            text     = entity.textGUI;
            textInfo = entity.textGUI.textInfo;
        }

        if (textInfo != null)
        {
            // find the closest link to our touch point
            float        minDistance = 999999;
            TMP_LinkInfo minLinkInfo = new TMP_LinkInfo();

            Transform rectTransform = text.transform;
            Vector3   position      = screenPoint;

            // Convert position into Worldspace coordinates
            TMP_TextUtilities.ScreenPointToWorldPointInRectangle(rectTransform, position, eventCamera, out position);

            for (int i = 0; i < text.textInfo.linkCount; i++)
            {
                TMP_LinkInfo linkInfo = text.textInfo.linkInfo [i];

                bool isBeginRegion = false;

                Vector3 bl = Vector3.zero;
                Vector3 tl = Vector3.zero;
                Vector3 br = Vector3.zero;
                Vector3 tr = Vector3.zero;

                // Iterate through each character of the word
                for (int j = 0; j < linkInfo.linkTextLength; j++)
                {
                    int characterIndex = linkInfo.linkTextfirstCharacterIndex + j;
                    TMP_CharacterInfo currentCharInfo = text.textInfo.characterInfo [characterIndex];
                    int currentLine = currentCharInfo.lineNumber;

                    // Check if Link characters are on the current page
                    if (text.overflowMode == TextOverflowModes.Page && currentCharInfo.pageNumber + 1 != text.pageToDisplay)
                    {
                        continue;
                    }

                    if (isBeginRegion == false)
                    {
                        isBeginRegion = true;

                        bl = rectTransform.TransformPoint(new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.descender, 0));
                        tl = rectTransform.TransformPoint(new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.ascender, 0));

                        // If Word is one character
                        if (linkInfo.linkTextLength == 1)
                        {
                            isBeginRegion = false;

                            br = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.descender, 0));
                            tr = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.ascender, 0));

                            // Check for Intersection
                            IsCloserToPoint(position, bl, linkInfo, ref minDistance, ref minLinkInfo);
                            IsCloserToPoint(position, tl, linkInfo, ref minDistance, ref minLinkInfo);
                            IsCloserToPoint(position, tr, linkInfo, ref minDistance, ref minLinkInfo);
                            IsCloserToPoint(position, br, linkInfo, ref minDistance, ref minLinkInfo);
                            IsCloserToPoint(position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo);
                        }
                    }

                    // Last Character of Word
                    if (isBeginRegion && j == linkInfo.linkTextLength - 1)
                    {
                        isBeginRegion = false;

                        br = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.descender, 0));
                        tr = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.ascender, 0));

                        IsCloserToPoint(position, bl, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, tl, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, tr, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, br, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo);
                    }
                    // If Word is split on more than one line.
                    else if (isBeginRegion && currentLine != text.textInfo.characterInfo [characterIndex + 1].lineNumber)
                    {
                        isBeginRegion = false;

                        br = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.descender, 0));
                        tr = rectTransform.TransformPoint(new Vector3(currentCharInfo.topRight.x, currentCharInfo.ascender, 0));

                        IsCloserToPoint(position, bl, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, tl, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, tr, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, br, linkInfo, ref minDistance, ref minLinkInfo);
                        IsCloserToPoint(position, (bl + br + tl + tr) * 0.25f, linkInfo, ref minDistance, ref minLinkInfo);
                    }
                }
            }

            int linkIdx = Array.IndexOf(text.textInfo.linkInfo, minLinkInfo);
            if (linkIdx >= 0)
            {
                if (block != null)
                {
                    block(minLinkInfo.GetLinkText(), linkIdx);
                }
                return(true);
            }
        }

        return(false);
    }
Example #12
0
        //TODO: Currently this doesn't work on a folder that has no textures in it.
        public void LoadCustomFolderSprite(ICustomFolderInfo folder, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var folderIconPath = Path.Combine(path, "folder.png");

            if (!File.Exists(folderIconPath))
            {
                folderIconPath = Path.Combine(path, "folder.jpg");
            }

            if (!File.Exists(folderIconPath))
            {
                folderIconPath = Path.Combine(path, "folder.jpeg");
            }

            if (!File.Exists(folderIconPath))
            {
                return;
            }

            // Assign new Sprite Sheet texture to the Sprite Asset.
            var texture = LoadTexture(folderIconPath);

            List <TMP_Sprite> spriteInfoList = new List <TMP_Sprite>();

            TMP_Sprite sprite = new TMP_Sprite();

            sprite.id       = 0;
            sprite.name     = Path.GetFileNameWithoutExtension(folderIconPath) ?? "";
            sprite.hashCode = TMP_TextUtilities.GetSimpleHashCode(sprite.name);

            //// Attempt to extract Unicode value from name
            int unicode;
            int indexOfSeperator = sprite.name.IndexOf('-');

            if (indexOfSeperator != -1)
            {
                unicode = TMP_TextUtilities.StringHexToInt(sprite.name.Substring(indexOfSeperator + 1));
            }
            else
            {
                unicode = TMP_TextUtilities.StringHexToInt(sprite.name);
            }

            sprite.unicode = unicode;

            sprite.x      = 0;
            sprite.y      = 0;
            sprite.width  = texture.width;
            sprite.height = texture.height;
            sprite.pivot  = new Vector2(0.5f, 0.5f);

            sprite.xAdvance = sprite.width;
            sprite.scale    = 1.0f;
            sprite.xOffset  = 0 - (sprite.width * sprite.pivot.x);
            sprite.yOffset  = sprite.height;

            spriteInfoList.Add(sprite);

            // Create new Sprite Asset using this texture
            TMP_SpriteAsset spriteAsset = ScriptableObject.CreateInstance <TMP_SpriteAsset>();

            // Compute the hash code for the sprite asset.
            spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name);

            spriteAsset.spriteSheet    = texture;
            spriteAsset.spriteInfoList = spriteInfoList;

            // Add new default material for sprite asset.
            AddDefaultMaterial(spriteAsset);

            folder.CustomSprite = spriteAsset;
        }
        List <TMP_Sprite> CreateSpriteInfoList(TexturePacker.SpriteDataObject spriteDataObject)
#endif
        {
#if TMP_2_1_0_PREVIEW_1_OR_NEWER
            List <TexturePacker_JsonArray.Frame> importedSprites = spriteDataObject.frames;
#else
            List <TexturePacker.SpriteData> importedSprites = spriteDataObject.frames;
#endif

            List <TMP_Sprite> spriteInfoList = new List <TMP_Sprite>();

            for (int i = 0; i < importedSprites.Count; i++)
            {
                TMP_Sprite sprite = new TMP_Sprite();

                sprite.id       = i;
                sprite.name     = Path.GetFileNameWithoutExtension(importedSprites[i].filename) ?? "";
                sprite.hashCode = TMP_TextUtilities.GetSimpleHashCode(sprite.name);

                // Attempt to extract Unicode value from name
                int unicode;
                int indexOfSeparator = sprite.name.IndexOf('-');
                if (indexOfSeparator != -1)
                {
                    string substring = sprite.name.Substring(0, indexOfSeparator);
#if TMP_1_4_0_OR_NEWER
                    unicode = TMP_TextUtilities.StringHexToInt(substring);
#else
                    unicode = TMP_TextUtilities.StringToInt(substring);
#endif
                }
                else
                {
#if TMP_1_4_0_OR_NEWER
                    unicode = TMP_TextUtilities.StringHexToInt(sprite.name);
#else
                    unicode = TMP_TextUtilities.StringToInt(sprite.name);
#endif
                }

                sprite.unicode = unicode;

                sprite.x      = importedSprites[i].frame.x;
                sprite.y      = m_SpriteAtlas.height - (importedSprites[i].frame.y + importedSprites[i].frame.h);
                sprite.width  = importedSprites[i].frame.w;
                sprite.height = importedSprites[i].frame.h;

                //Calculate sprite pivot position
                sprite.pivot = importedSprites[i].pivot;

                //Extra Properties
                //var scaledOffset = (sprite.height * ((m_globalGlyphScale - 1) * 0.5f)) * sprite.pivot.y;
                sprite.xAdvance = sprite.width;
#if TMP_1_4_0_OR_NEWER
                sprite.scale = 1.0f;
#else
                sprite.scale = m_globalGlyphScale;
#endif
                sprite.xOffset = 0 - (sprite.width * sprite.pivot.x);
                sprite.yOffset = sprite.height - (sprite.height * sprite.pivot.y);
                spriteInfoList.Add(sprite);
            }

            return(spriteInfoList);
        }
Example #14
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_Unicode    = property.FindPropertyRelative("m_Unicode");
            SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_GlyphIndex");
            SerializedProperty prop_Scale      = property.FindPropertyRelative("m_Scale");


            GUIStyle style = new GUIStyle(EditorStyles.label);

            style.richText = true;

            EditorGUIUtility.labelWidth = 40f;
            EditorGUIUtility.fieldWidth = 50;

            Rect rect = new Rect(position.x + 50, position.y, position.width, 49);

            // Display non-editable fields
            if (GUI.enabled == false)
            {
                int unicode = prop_Unicode.intValue;
                EditorGUI.LabelField(new Rect(rect.x, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + unicode.ToString("X") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x + 115, rect.y, 120f, 18), unicode <= 0xFFFF ? new GUIContent("UTF16: <color=#FFFF80>\\u" + unicode.ToString("X4") + "</color>") : new GUIContent("UTF32: <color=#FFFF80>\\U" + unicode.ToString("X8") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_GlyphIndex.intValue + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_Scale.floatValue + "</color>"), style);

                // Draw Glyph (if exists)
                DrawGlyph(position, property);
            }
            else // Display editable fields
            {
                EditorGUIUtility.labelWidth = 55f;
                GUI.SetNextControlName("Unicode Input");
                EditorGUI.BeginChangeCheck();
                string unicode = EditorGUI.TextField(new Rect(rect.x, rect.y, 120, 18), "Unicode:", prop_Unicode.intValue.ToString("X"));

                if (GUI.GetNameOfFocusedControl() == "Unicode Input")
                {
                    //Filter out unwanted characters.
                    char chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                    {
                        Event.current.character = '\0';
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    // Update Unicode value
                    prop_Unicode.intValue = TMP_TextUtilities.StringHexToInt(unicode);
                }

                // Cache current glyph index in case it needs to be restored if the new glyph index is invalid.
                int currentGlyphIndex = prop_GlyphIndex.intValue;

                EditorGUIUtility.labelWidth = 59f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_GlyphIndex, new GUIContent("Glyph ID:"));
                if (EditorGUI.EndChangeCheck())
                {
                    // Get a reference to the font asset
                    TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset;

                    // Make sure new glyph index is valid.
                    int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == prop_GlyphIndex.intValue);

                    if (elementIndex == -1)
                    {
                        prop_GlyphIndex.intValue = currentGlyphIndex;
                    }
                    else
                    {
                        fontAsset.m_IsFontAssetLookupTablesDirty = true;
                    }
                }

                int glyphIndex = prop_GlyphIndex.intValue;

                // Reset glyph selection if new character has been selected.
                if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex)
                {
                    m_GlyphSelectedForEditing = -1;
                }

                // Display button to edit the glyph data.
                if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph")))
                {
                    if (m_GlyphSelectedForEditing == -1)
                    {
                        m_GlyphSelectedForEditing = glyphIndex;
                    }
                    else
                    {
                        m_GlyphSelectedForEditing = -1;
                    }

                    // Button clicks should not result in potential change.
                    GUI.changed = false;
                }

                // Show the glyph property drawer if selected
                if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled)
                {
                    // Get a reference to the font asset
                    TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset;

                    if (fontAsset != null)
                    {
                        // Get the index of the glyph in the font asset glyph table.
                        int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == glyphIndex);

                        if (elementIndex != -1)
                        {
                            SerializedProperty prop_GlyphTable = property.serializedObject.FindProperty("m_GlyphTable");
                            SerializedProperty prop_Glyph      = prop_GlyphTable.GetArrayElementAtIndex(elementIndex);

                            SerializedProperty prop_GlyphMetrics = prop_Glyph.FindPropertyRelative("m_Metrics");
                            SerializedProperty prop_GlyphRect    = prop_Glyph.FindPropertyRelative("m_GlyphRect");

                            Rect newRect = EditorGUILayout.GetControlRect(false, 115);
                            EditorGUI.DrawRect(new Rect(newRect.x + 52, newRect.y - 20, newRect.width - 52, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f));
                            EditorGUI.DrawRect(new Rect(newRect.x + 53, newRect.y - 19, newRect.width - 54, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f));

                            // Display GlyphRect
                            newRect.x     += 55;
                            newRect.y     -= 18;
                            newRect.width += 5;
                            EditorGUI.PropertyField(newRect, prop_GlyphRect);

                            // Display GlyphMetrics
                            newRect.y += 45;
                            EditorGUI.PropertyField(newRect, prop_GlyphMetrics);

                            rect.y += 120;
                        }
                    }
                }

                EditorGUIUtility.labelWidth = 39f;
                EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_Scale, new GUIContent("Scale:"));

                // Draw Glyph (if exists)
                DrawGlyph(position, property);
            }
        }
Example #15
0
        protected virtual void BaseOnPointerDown(PointerEventData eventData)
        {
#if FIX_NEW_INPUTSYSTEM_SUPPORT
            if (!MayDrag(eventData))
            {
                return;
            }

            EventSystem.current.SetSelectedGameObject(gameObject, eventData);

            bool hadFocusBefore = AllowInput;
            BaseSelectableOnPointerDown(eventData);

            if (InPlaceEditing() == false)
            {
                if (m_SoftKeyboard == null || !m_SoftKeyboard.active)
                {
                    OnSelect(eventData);
                    return;
                }
            }

            Event.PopEvent(ProcessingEvent);
            bool shift = ProcessingEvent != null && (ProcessingEvent.modifiers & EventModifiers.Shift) != 0;

            // Check for Double Click
            bool  isDoubleClick = false;
            float timeStamp     = Time.unscaledTime;

            if (PointerDownClickStartTime + DoubleClickDelay > timeStamp)
            {
                isDoubleClick = true;
            }

            PointerDownClickStartTime = timeStamp;

            // Only set caret position if we didn't just get focus now.
            // Otherwise it will overwrite the select all on focus.
            if (hadFocusBefore || !m_OnFocusSelectAll)
            {
                CaretPosition insertionSide;

                int insertionIndex = TMP_TextUtilities.GetCursorIndexFromPosition(m_TextComponent, eventData.position, eventData.pressEventCamera, out insertionSide);

                if (shift)
                {
                    if (m_isRichTextEditingAllowed)
                    {
                        if (insertionSide == CaretPosition.Left)
                        {
                            stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
                        }
                        else if (insertionSide == CaretPosition.Right)
                        {
                            stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
                        }
                    }
                    else
                    {
                        if (insertionSide == CaretPosition.Left)
                        {
                            stringSelectPositionInternal = insertionIndex == 0
                                ? m_TextComponent.textInfo.characterInfo[0].index
                                : m_TextComponent.textInfo.characterInfo[insertionIndex - 1].index + m_TextComponent.textInfo.characterInfo[insertionIndex - 1].stringLength;
                        }
                        else if (insertionSide == CaretPosition.Right)
                        {
                            stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
                        }
                    }
                }
                else
                {
                    if (m_isRichTextEditingAllowed)
                    {
                        if (insertionSide == CaretPosition.Left)
                        {
                            stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
                        }
                        else if (insertionSide == CaretPosition.Right)
                        {
                            stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
                        }
                    }
                    else
                    {
                        if (insertionSide == CaretPosition.Left)
                        {
                            stringPositionInternal = stringSelectPositionInternal = insertionIndex == 0
                                ? m_TextComponent.textInfo.characterInfo[0].index
                                : m_TextComponent.textInfo.characterInfo[insertionIndex - 1].index + m_TextComponent.textInfo.characterInfo[insertionIndex - 1].stringLength;
                        }
                        else if (insertionSide == CaretPosition.Right)
                        {
                            stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
                        }
                    }
                }


                if (isDoubleClick)
                {
                    int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, eventData.position, eventData.pressEventCamera);

                    if (wordIndex != -1)
                    {
                        // TODO: Should behavior be different if rich text editing is enabled or not?

                        // Select current word
                        caretPositionInternal       = m_TextComponent.textInfo.wordInfo[wordIndex].firstCharacterIndex;
                        caretSelectPositionInternal = m_TextComponent.textInfo.wordInfo[wordIndex].lastCharacterIndex + 1;

                        stringPositionInternal       = m_TextComponent.textInfo.characterInfo[caretPositionInternal].index;
                        stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].index + m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].stringLength;
                    }
                    else
                    {
                        // Select current character
                        caretPositionInternal       = insertionIndex;
                        caretSelectPositionInternal = caretPositionInternal + 1;

                        stringPositionInternal       = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
                        stringSelectPositionInternal = stringPositionInternal + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
                    }
                }
                else
                {
                    caretPositionInternal = caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringPositionInternal);
                }

                m_isSelectAll = false;
            }

            UpdateLabel();
            eventData.Use();
#else
            base.OnPointerDown(eventData);
#endif
        }
Example #16
0
        void LateUpdate()
        {
            if (isHoveringObject)
            {
                // Check if Mouse Intersects any of the characters. If so, assign a random color.
                #region Handle Character Selection
                int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);

                if (charIndex != -1 && charIndex != m_lastIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
                {
                    m_lastIndex = charIndex;

                    Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);

                    int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;

                    //UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo[0].uiVertices;
                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[0].colors32;

                    vertexColors[vertexIndex + 0] = c;
                    vertexColors[vertexIndex + 1] = c;
                    vertexColors[vertexIndex + 2] = c;
                    vertexColors[vertexIndex + 3] = c;

                    if (m_TextMeshPro.textInfo.characterInfo[charIndex].elementType == TMP_TextElementType.Character)
                    {
                        Mesh mesh = m_TextMeshPro.textInfo.meshInfo[0].mesh;
                        mesh.colors32 = vertexColors;

                        m_TextMeshPro.canvasRenderer.SetMesh(mesh);
                    }
                    else if (m_TextMeshPro.textInfo.characterInfo[charIndex].elementType == TMP_TextElementType.Sprite)
                    {
                        // TODO Fix for Sprites
                        //m_TextMeshPro.inlineGraphicManager.inlineGraphic.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
                    }
                }
                #endregion


                #region Word Selection Handling
                //Check if Mouse intersects any words and if so assign a random color to that word.
                int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);

                // Clear previous word selection.
                if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
                {
                    TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];

                    // Get a reference to the vertex color
                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[0].colors32;

                    // Iterate through each of the characters of the word.
                    for (int i = 0; i < wInfo.characterCount; i++)
                    {
                        int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;

                        Color32 c = vertexColors[vertexIndex + 0].Tint(1.33333f);

                        vertexColors[vertexIndex + 0] = c;
                        vertexColors[vertexIndex + 1] = c;
                        vertexColors[vertexIndex + 2] = c;
                        vertexColors[vertexIndex + 3] = c;
                    }

                    Mesh mesh = m_TextMeshPro.textInfo.meshInfo[0].mesh;
                    mesh.colors32 = vertexColors;

                    m_TextMeshPro.canvasRenderer.SetMesh(mesh);

                    m_selectedWord = -1;
                }


                // Word Selection Handling
                if (wordIndex != -1 && wordIndex != m_selectedWord && !(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
                {
                    m_selectedWord = wordIndex;

                    TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];

                    // Get a reference to the vertex color
                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[0].colors32;

                    // Iterate through each of the characters of the word.
                    for (int i = 0; i < wInfo.characterCount; i++)
                    {
                        int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;

                        Color32 c = vertexColors[vertexIndex + 0].Tint(0.75f);

                        vertexColors[vertexIndex + 0] = c;
                        vertexColors[vertexIndex + 1] = c;
                        vertexColors[vertexIndex + 2] = c;
                        vertexColors[vertexIndex + 3] = c;
                    }

                    Mesh mesh = m_TextMeshPro.textInfo.meshInfo[0].mesh;
                    mesh.colors32 = vertexColors;

                    m_TextMeshPro.canvasRenderer.SetMesh(mesh);
                }
                #endregion


                #region Example of Link Handling
                // Check if mouse intersects with any links.
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);

                // Clear previous link selection if one existed.
                if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
                {
                    m_TextPopup_RectTransform.gameObject.SetActive(false);
                    m_selectedLink = -1;
                }

                // Handle new Link selection.
                if (linkIndex != -1 && linkIndex != m_selectedLink)
                {
                    m_selectedLink = linkIndex;

                    TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
                    //int linkHashCode = linkInfo.hashCode;

                    //Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\"   Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.

                    Vector3 worldPointInRectangle = Vector3.zero;
                    RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);

                    switch (linkInfo.GetLinkID())
                    {
                    case "id_01":     // 100041637: // id_01
                        m_TextPopup_RectTransform.position = worldPointInRectangle;
                        m_TextPopup_RectTransform.gameObject.SetActive(true);
                        m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
                        break;

                    case "id_02":     // 100041638: // id_02
                        m_TextPopup_RectTransform.position = worldPointInRectangle;
                        m_TextPopup_RectTransform.gameObject.SetActive(true);
                        m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
                        break;
                    }
                }
                #endregion
            }
        }
Example #17
0
        public override void OnInspectorGUI()
        {
            // Check Warnings


            //Debug.Log("OnInspectorGUI Called.");
            Event currentEvent = Event.current;

            serializedObject.Update();

            // TextMeshPro Font Info Panel
            Rect rect = EditorGUILayout.GetControlRect();


            GUI.Label(rect, "Face Info", EditorStyles.boldLabel);

            rect.x    += rect.width - 130f;
            rect.width = 130f;

            if (GUI.Button(rect, "Update Atlas Texture"))
            {
                TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(target as TMP_FontAsset);
            }


            EditorGUI.indentLevel = 1;

            GUI.enabled = false; // Lock UI

            float labelWidth = EditorGUIUtility.labelWidth;
            float fieldWidth = EditorGUIUtility.fieldWidth;

            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize"));

            GUI.enabled = true;
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Scale"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight"));

            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("CapHeight"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline"), new GUIContent("Underline Offset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("strikethrough"), new GUIContent("Strikethrough Offset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset"));

            SerializedProperty subSize_prop = m_fontInfo_prop.FindPropertyRelative("SubSize");

            EditorGUILayout.PropertyField(subSize_prop, new GUIContent("Super / Subscript Size"));
            subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f);


            GUI.enabled = false;
            //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));

            //GUILayout.label("Atlas Size");
            EditorGUI.indentLevel = 1;
            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width"));
            EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height"));

            GUI.enabled = true;

            EditorGUILayout.Space();

            EditorGUI.indentLevel            = 0;
            UI_PanelState.fontSubAssetsPanel = EditorGUILayout.Foldout(UI_PanelState.fontSubAssetsPanel, new GUIContent("Font Sub-Assets"), true, TMP_UIStyleManager.boldFoldout);

            if (UI_PanelState.fontSubAssetsPanel)
            {
                GUI.enabled           = false;
                EditorGUI.indentLevel = 1;
                EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas"));
                EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material"));
                GUI.enabled = true;
                EditorGUILayout.Space();
            }

            string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events

            // FONT SETTINGS
            EditorGUI.indentLevel         = 0;
            UI_PanelState.fontWeightPanel = EditorGUILayout.Foldout(UI_PanelState.fontWeightPanel, new GUIContent("Font Weights", "The Font Assets that will be used for different font weights and the settings used to simulate a typeface when no asset is available."), true, TMP_UIStyleManager.boldFoldout);

            if (UI_PanelState.fontWeightPanel)
            {
                EditorGUIUtility.labelWidth *= 0.75f;
                EditorGUIUtility.fieldWidth *= 0.25f;

                EditorGUILayout.BeginVertical();
                EditorGUI.indentLevel = 1;
                rect       = EditorGUILayout.GetControlRect(true);
                rect.x    += EditorGUIUtility.labelWidth;
                rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
                GUI.Label(rect, "Normal Style", EditorStyles.boldLabel);
                rect.x += rect.width;
                GUI.Label(rect, "Italic Style", EditorStyles.boldLabel);

                EditorGUI.indentLevel = 1;

                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(1), new GUIContent("100 - Thin"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(2), new GUIContent("200 - Extra-Light"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(3), new GUIContent("300 - Light"));
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(5), new GUIContent("500 - Medium"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(6), new GUIContent("600 - Demi-Bold"));
                EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(8), new GUIContent("800 - Heavy"));
                //EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(9), new GUIContent("900 - Black"));

                EditorGUILayout.EndVertical();

                EditorGUILayout.Space();

                EditorGUILayout.BeginVertical();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight"));
                font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;

                    // Modify the material property on matching material presets.
                    for (int i = 0; i < m_materialPresets.Length; i++)
                    {
                        m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
                    }
                }

                EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight"));
                font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;

                    // Modify the material property on matching material presets.
                    for (int i = 0; i < m_materialPresets.Length; i++)
                    {
                        m_materialPresets[i].SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
                    }
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Spacing Offset"));
                font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100, 100);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;
                }

                EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing"));
                font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100);
                if (GUI.changed || evt_cmd == k_UndoRedo)
                {
                    GUI.changed = false;
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style"));
                font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);

                EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple"));
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }

            EditorGUIUtility.labelWidth = 0;
            EditorGUIUtility.fieldWidth = 0;

            // FALLBACK FONT ASSETS
            EditorGUI.indentLevel = 0;
            UI_PanelState.fallbackFontAssetPanel = EditorGUILayout.Foldout(UI_PanelState.fallbackFontAssetPanel, new GUIContent("Fallback Font Assets", "Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset."), true, TMP_UIStyleManager.boldFoldout);

            if (UI_PanelState.fallbackFontAssetPanel)
            {
                EditorGUIUtility.labelWidth = 120;
                EditorGUI.indentLevel       = 0;

                m_list.DoLayoutList();
                EditorGUILayout.Space();
            }

            // GLYPH INFO TABLE
            #region Glyph Table
            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUIUtility.fieldWidth = fieldWidth;
            EditorGUI.indentLevel       = 0;

            UI_PanelState.glyphInfoPanel = EditorGUILayout.Foldout(UI_PanelState.glyphInfoPanel, new GUIContent("Glyph Table"), true, TMP_UIStyleManager.boldFoldout);

            if (UI_PanelState.glyphInfoPanel)
            {
                int arraySize    = m_glyphInfoList_prop.arraySize;
                int itemsPerPage = 15;

                // Display Glyph Management Tools
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    // Search Bar implementation
                    #region DISPLAY SEARCH BAR
                    EditorGUILayout.BeginHorizontal();
                    {
                        EditorGUIUtility.labelWidth = 130f;
                        EditorGUI.BeginChangeCheck();
                        string searchPattern = EditorGUILayout.TextField("Glyph Search", m_GlyphSearchPattern, "SearchTextField");
                        if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
                        {
                            if (string.IsNullOrEmpty(searchPattern) == false)
                            {
                                m_GlyphSearchPattern = searchPattern;

                                // Search Glyph Table for potential matches
                                SearchGlyphTable(m_GlyphSearchPattern, ref m_GlyphSearchList);
                            }
                            else
                            {
                                m_GlyphSearchPattern = null;
                            }

                            m_isSearchDirty = false;
                        }

                        string styleName = string.IsNullOrEmpty(m_GlyphSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
                        if (GUILayout.Button(GUIContent.none, styleName))
                        {
                            GUIUtility.keyboardControl = 0;
                            m_GlyphSearchPattern       = string.Empty;
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                    #endregion

                    // Display Page Navigation
                    if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
                    {
                        arraySize = m_GlyphSearchList.Count;
                    }

                    DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);
                }
                EditorGUILayout.EndVertical();

                // Display Glyph Table Elements

                if (arraySize > 0)
                {
                    // Display each GlyphInfo entry using the GlyphInfo property drawer.
                    for (int i = itemsPerPage * m_CurrentGlyphPage; i < arraySize && i < itemsPerPage * (m_CurrentGlyphPage + 1); i++)
                    {
                        // Define the start of the selection region of the element.
                        Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        int elementIndex = i;
                        if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
                        {
                            elementIndex = m_GlyphSearchList[i];
                        }

                        SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(elementIndex);

                        EditorGUILayout.BeginVertical(EditorStyles.helpBox);

                        EditorGUI.BeginDisabledGroup(i != m_SelectedGlyphRecord);
                        {
                            EditorGUILayout.PropertyField(glyphInfo);
                        }
                        EditorGUI.EndDisabledGroup();

                        EditorGUILayout.EndVertical();

                        // Define the end of the selection region of the element.
                        Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        // Check for Item selection
                        Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
                        if (DoSelectionCheck(selectionArea))
                        {
                            if (m_SelectedGlyphRecord == i)
                            {
                                m_SelectedGlyphRecord = -1;
                            }
                            else
                            {
                                m_SelectedGlyphRecord       = i;
                                m_AddGlyphWarning.isEnabled = false;
                                m_unicodeHexLabel           = k_placeholderUnicodeHex;
                                GUIUtility.keyboardControl  = 0;
                            }
                        }

                        // Draw Selection Highlight and Glyph Options
                        if (m_SelectedGlyphRecord == i)
                        {
                            TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));

                            // Draw Glyph management options
                            Rect  controlRect     = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
                            float optionAreaWidth = controlRect.width * 0.6f;
                            float btnWidth        = optionAreaWidth / 3;

                            Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height);

                            // Copy Selected Glyph to Target Glyph ID
                            GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID);
                            if (GUI.Button(position, new GUIContent("Copy to")))
                            {
                                GUIUtility.keyboardControl = 0;

                                // Convert Hex Value to Decimal
                                int dstGlyphID = TMP_TextUtilities.StringToInt(m_dstGlyphID);

                                //Add new glyph at target Unicode hex id.
                                if (!AddNewGlyph(elementIndex, dstGlyphID))
                                {
                                    m_AddGlyphWarning.isEnabled      = true;
                                    m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1;
                                }

                                m_dstGlyphID    = string.Empty;
                                m_isSearchDirty = true;

                                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
                            }

                            // Target Glyph ID
                            GUI.enabled = true;
                            position.x += btnWidth;

                            GUI.SetNextControlName("GlyphID_Input");
                            m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID);

                            // Placeholder text
                            EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Glyph"), TMP_UIStyleManager.label);

                            // Only filter the input when the destination glyph ID text field has focus.
                            if (GUI.GetNameOfFocusedControl() == "GlyphID_Input")
                            {
                                m_unicodeHexLabel = string.Empty;

                                //Filter out unwanted characters.
                                char chr = Event.current.character;
                                if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                                {
                                    Event.current.character = '\0';
                                }
                            }
                            else
                            {
                                m_unicodeHexLabel = k_placeholderUnicodeHex;
                            }


                            // Remove Glyph
                            position.x += btnWidth;
                            if (GUI.Button(position, "Remove"))
                            {
                                GUIUtility.keyboardControl = 0;

                                RemoveGlyphFromList(elementIndex);

                                isAssetDirty          = true;
                                m_SelectedGlyphRecord = -1;
                                m_isSearchDirty       = true;
                                break;
                            }

                            if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime)
                            {
                                EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning);
                            }
                        }
                    }
                }

                DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);

                EditorGUILayout.Space();
            }
            #endregion


            // KERNING TABLE PANEL
            #region Kerning Table
            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUIUtility.fieldWidth = fieldWidth;
            EditorGUI.indentLevel       = 0;

            UI_PanelState.kerningInfoPanel = EditorGUILayout.Foldout(UI_PanelState.kerningInfoPanel, new GUIContent("Glyph Adjustment Table"), true, TMP_UIStyleManager.boldFoldout);

            if (UI_PanelState.kerningInfoPanel)
            {
                int arraySize    = m_kerningPairs_prop.arraySize;
                int itemsPerPage = 20;

                // Display Kerning Pair Management Tools
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    // Search Bar implementation
                    #region DISPLAY SEARCH BAR
                    EditorGUILayout.BeginHorizontal();
                    {
                        EditorGUIUtility.labelWidth = 150f;
                        EditorGUI.BeginChangeCheck();
                        string searchPattern = EditorGUILayout.TextField("Adjustment Pair Search", m_KerningTableSearchPattern, "SearchTextField");
                        if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
                        {
                            if (string.IsNullOrEmpty(searchPattern) == false)
                            {
                                m_KerningTableSearchPattern = searchPattern;

                                // Search Glyph Table for potential matches
                                SearchKerningTable(m_KerningTableSearchPattern, ref m_KerningTableSearchList);
                            }
                            else
                            {
                                m_KerningTableSearchPattern = null;
                            }

                            m_isSearchDirty = false;
                        }

                        string styleName = string.IsNullOrEmpty(m_KerningTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
                        if (GUILayout.Button(GUIContent.none, styleName))
                        {
                            GUIUtility.keyboardControl  = 0;
                            m_KerningTableSearchPattern = string.Empty;
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                    #endregion

                    // Display Page Navigation
                    if (!string.IsNullOrEmpty(m_KerningTableSearchPattern))
                    {
                        arraySize = m_KerningTableSearchList.Count;
                    }

                    DisplayPageNavigation(ref m_CurrentKerningPage, arraySize, itemsPerPage);
                }
                EditorGUILayout.EndVertical();


                //Rect pos;
                //pos = EditorGUILayout.GetControlRect(false, 20);

                //pos.x += 5;
                //EditorGUI.LabelField(pos, "First Glyph", TMP_UIStyleManager.TMP_GUISkin.label);
                //pos.x += 100;
                //EditorGUI.LabelField(pos, "Adjustment Values", TMP_UIStyleManager.TMP_GUISkin.label);

                //pos.x = pos.width / 2 + 5;
                //EditorGUI.LabelField(pos, "Second Glyph", TMP_UIStyleManager.TMP_GUISkin.label);
                //pos.x += 100;
                //EditorGUI.LabelField(pos, "Adjustment Values", TMP_UIStyleManager.TMP_GUISkin.label);

                if (arraySize > 0)
                {
                    // Display each GlyphInfo entry using the GlyphInfo property drawer.
                    for (int i = itemsPerPage * m_CurrentKerningPage; i < arraySize && i < itemsPerPage * (m_CurrentKerningPage + 1); i++)
                    {
                        // Define the start of the selection region of the element.
                        Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        int elementIndex = i;
                        if (!string.IsNullOrEmpty(m_KerningTableSearchPattern))
                        {
                            elementIndex = m_KerningTableSearchList[i];
                        }

                        SerializedProperty kerningInfo = m_kerningPairs_prop.GetArrayElementAtIndex(elementIndex);

                        EditorGUILayout.BeginVertical(EditorStyles.helpBox);

                        EditorGUI.BeginDisabledGroup(i != m_SelectedAdjustmentRecord);
                        {
                            EditorGUILayout.PropertyField(kerningInfo, new GUIContent("Selectable"));
                        }
                        EditorGUI.EndDisabledGroup();

                        EditorGUILayout.EndVertical();

                        // Define the end of the selection region of the element.
                        Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));

                        // Check for Item selection
                        Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
                        if (DoSelectionCheck(selectionArea))
                        {
                            if (m_SelectedAdjustmentRecord == i)
                            {
                                m_SelectedAdjustmentRecord = -1;
                            }
                            else
                            {
                                m_SelectedAdjustmentRecord = i;
                                GUIUtility.keyboardControl = 0;
                            }
                        }

                        // Draw Selection Highlight and Kerning Pair Options
                        if (m_SelectedAdjustmentRecord == i)
                        {
                            TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));

                            // Draw Glyph management options
                            Rect  controlRect     = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
                            float optionAreaWidth = controlRect.width;
                            float btnWidth        = optionAreaWidth / 4;

                            Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height);

                            // Remove Kerning pair
                            GUI.enabled = true;
                            if (GUI.Button(position, "Remove"))
                            {
                                GUIUtility.keyboardControl = 0;

                                m_kerningTable.RemoveKerningPair(i);
                                m_fontAsset.ReadFontDefinition();

                                isAssetDirty = true;
                                m_SelectedAdjustmentRecord = -1;
                                m_isSearchDirty            = true;
                                break;
                            }
                        }
                    }
                }

                DisplayPageNavigation(ref m_CurrentKerningPage, arraySize, itemsPerPage);

                GUILayout.Space(5);

                // Add new kerning pair
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    EditorGUILayout.PropertyField(m_kerningPair_prop);
                }
                EditorGUILayout.EndVertical();

                if (GUILayout.Button("Add New Kerning Pair"))
                {
                    int firstGlyph  = m_kerningPair_prop.FindPropertyRelative("m_FirstGlyph").intValue;
                    int secondGlyph = m_kerningPair_prop.FindPropertyRelative("m_SecondGlyph").intValue;

                    GlyphValueRecord firstGlyphAdjustments  = GetGlyphAdjustments(m_kerningPair_prop.FindPropertyRelative("m_FirstGlyphAdjustments"));
                    GlyphValueRecord secondGlyphAdjustments = GetGlyphAdjustments(m_kerningPair_prop.FindPropertyRelative("m_SecondGlyphAdjustments"));

                    errorCode = m_kerningTable.AddGlyphPairAdjustmentRecord((uint)firstGlyph, firstGlyphAdjustments, (uint)secondGlyph, secondGlyphAdjustments);

                    // Sort Kerning Pairs & Reload Font Asset if new kerning pair was added.
                    if (errorCode != -1)
                    {
                        m_kerningTable.SortKerningPairs();
                        m_fontAsset.ReadFontDefinition();
                        serializedObject.ApplyModifiedProperties();
                        isAssetDirty    = true;
                        m_isSearchDirty = true;
                    }
                    else
                    {
                        timeStamp = System.DateTime.Now.AddSeconds(5);
                    }

                    // Clear Add Kerning Pair Panel
                    // TODO
                }

                if (errorCode == -1)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.label);
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();

                    if (System.DateTime.Now > timeStamp)
                    {
                        errorCode = 0;
                    }
                }
            }
            #endregion


            if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
            {
                TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);

                isAssetDirty = false;
                EditorUtility.SetDirty(target);
            }


            // Clear selection if mouse event was not consumed.
            GUI.enabled = true;
            if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
            {
                m_SelectedAdjustmentRecord = -1;
            }
        }
        public static void CreateSpriteAsset()
        {
            Object target = Selection.activeObject;

            if (target == null || target.GetType() != typeof(Texture2D)) // && target.GetType() != typeof(SpriteAtlas)))
            {
                Debug.LogWarning("A texture must first be selected in order to create a TextMesh Pro Sprite Asset.");
                return;
            }

            // Get the path to the selected asset.
            string filePathWithName         = AssetDatabase.GetAssetPath(target);
            string fileNameWithExtension    = Path.GetFileName(filePathWithName);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
            string filePath = filePathWithName.Replace(fileNameWithExtension, "");


            // Create new Sprite Asset
            TMP_SpriteAsset spriteAsset = ScriptableObject.CreateInstance <TMP_SpriteAsset>();

            AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset");

            spriteAsset.version = "1.1.0";

            // Compute the hash code for the sprite asset.
            spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name);

            List <TMP_SpriteGlyph>     spriteGlyphTable     = new List <TMP_SpriteGlyph>();
            List <TMP_SpriteCharacter> spriteCharacterTable = new List <TMP_SpriteCharacter>();

            if (target.GetType() == typeof(Texture2D))
            {
                Texture2D sourceTex = target as Texture2D;

                // Assign new Sprite Sheet texture to the Sprite Asset.
                spriteAsset.spriteSheet = sourceTex;

                PopulateSpriteTables(sourceTex, ref spriteCharacterTable, ref spriteGlyphTable);

                spriteAsset.spriteCharacterTable = spriteCharacterTable;
                spriteAsset.spriteGlyphTable     = spriteGlyphTable;

                // Add new default material for sprite asset.
                AddDefaultMaterial(spriteAsset);
            }
            else if (target.GetType() == typeof(SpriteAtlas))
            {
                //SpriteAtlas spriteAtlas = target as SpriteAtlas;

                //PopulateSpriteTables(spriteAtlas, ref spriteCharacterTable, ref spriteGlyphTable);

                //spriteAsset.spriteCharacterTable = spriteCharacterTable;
                //spriteAsset.spriteGlyphTable = spriteGlyphTable;

                //spriteAsset.spriteSheet = spriteGlyphTable[0].sprite.texture;

                //// Add new default material for sprite asset.
                //AddDefaultMaterial(spriteAsset);
            }

            // Update Lookup tables.
            spriteAsset.UpdateLookupTables();

            // Get the Sprites contained in the Sprite Sheet
            EditorUtility.SetDirty(spriteAsset);

            //spriteAsset.sprites = sprites;

            // Set source texture back to Not Readable.
            //texImporter.isReadable = false;

            AssetDatabase.SaveAssets();

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset));  // Re-import font asset to get the new updated version.

            //AssetDatabase.Refresh();
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_SpriteName         = property.FindPropertyRelative("m_Name");
            SerializedProperty prop_SpriteNameHashCode = property.FindPropertyRelative("m_HashCode");
            SerializedProperty prop_SpriteUnicode      = property.FindPropertyRelative("m_Unicode");
            SerializedProperty prop_SpriteGlyphIndex   = property.FindPropertyRelative("m_GlyphIndex");
            SerializedProperty prop_SpriteScale        = property.FindPropertyRelative("m_Scale");


            GUIStyle style = new GUIStyle(EditorStyles.label);

            style.richText = true;

            EditorGUIUtility.labelWidth = 40f;
            EditorGUIUtility.fieldWidth = 50;

            Rect rect = new Rect(position.x + 60, position.y, position.width, 49);

            // Display non-editable fields
            if (GUI.enabled == false)
            {
                // Sprite Character Index
                int spriteCharacterIndex;
                int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex);
                EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style);

                EditorGUI.LabelField(new Rect(rect.x + 75f, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + prop_SpriteUnicode.intValue.ToString("X") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), new GUIContent("Name: <color=#FFFF80>" + prop_SpriteName.stringValue + "</color>"), style);

                EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_SpriteGlyphIndex.intValue + "</color>"), style);

                // Draw Sprite Glyph (if exists)
                DrawSpriteGlyph(position, property);

                EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_SpriteScale.floatValue + "</color>"), style);
            }
            else // Display editable fields
            {
                // Get a reference to the underlying Sprite Asset
                TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset;

                // Sprite Character Index
                int spriteCharacterIndex;
                int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex);

                EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style);

                EditorGUIUtility.labelWidth = 55f;
                GUI.SetNextControlName("Unicode Input");
                EditorGUI.BeginChangeCheck();
                string unicode = EditorGUI.DelayedTextField(new Rect(rect.x + 75f, rect.y, 120, 18), "Unicode:", prop_SpriteUnicode.intValue.ToString("X"));

                if (GUI.GetNameOfFocusedControl() == "Unicode Input")
                {
                    //Filter out unwanted characters.
                    char chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                    {
                        Event.current.character = '\0';
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    // Update Unicode value
                    prop_SpriteUnicode.intValue = TMP_TextUtilities.StringHexToInt(unicode);
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                EditorGUIUtility.labelWidth = 41f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedTextField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), prop_SpriteName, new GUIContent("Name:"));
                if (EditorGUI.EndChangeCheck())
                {
                    // Recompute hashCode for new name
                    prop_SpriteNameHashCode.intValue             = TMP_TextUtilities.GetSimpleHashCode(prop_SpriteName.stringValue);
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                EditorGUIUtility.labelWidth = 59f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_SpriteGlyphIndex, new GUIContent("Glyph ID:"));
                if (EditorGUI.EndChangeCheck())
                {
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                // Draw Sprite Glyph (if exists)
                DrawSpriteGlyph(position, property);

                int glyphIndex = prop_SpriteGlyphIndex.intValue;

                // Reset glyph selection if new character has been selected.
                if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex)
                {
                    m_GlyphSelectedForEditing = -1;
                }

                // Display button to edit the glyph data.
                if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph")))
                {
                    if (m_GlyphSelectedForEditing == -1)
                    {
                        m_GlyphSelectedForEditing = glyphIndex;
                    }
                    else
                    {
                        m_GlyphSelectedForEditing = -1;
                    }

                    // Button clicks should not result in potential change.
                    GUI.changed = false;
                }

                // Show the glyph property drawer if selected
                if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled)
                {
                    if (spriteAsset != null)
                    {
                        // Lookup glyph and draw glyph (if available)
                        int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex);

                        if (elementIndex != -1)
                        {
                            // Get a reference to the Sprite Glyph Table
                            SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable");

                            SerializedProperty prop_SpriteGlyph  = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex);
                            SerializedProperty prop_GlyphMetrics = prop_SpriteGlyph.FindPropertyRelative("m_Metrics");
                            SerializedProperty prop_GlyphRect    = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect");

                            Rect newRect = EditorGUILayout.GetControlRect(false, 115);
                            EditorGUI.DrawRect(new Rect(newRect.x + 62, newRect.y - 20, newRect.width - 62, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f));
                            EditorGUI.DrawRect(new Rect(newRect.x + 63, newRect.y - 19, newRect.width - 64, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f));

                            // Display GlyphRect
                            newRect.x     += 65;
                            newRect.y     -= 18;
                            newRect.width += 5;
                            EditorGUI.PropertyField(newRect, prop_GlyphRect);

                            // Display GlyphMetrics
                            newRect.y += 45;
                            EditorGUI.PropertyField(newRect, prop_GlyphMetrics);

                            rect.y += 120;
                        }
                    }
                }

                EditorGUIUtility.labelWidth = 39f;
                EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_SpriteScale, new GUIContent("Scale:"));
            }
        }
Example #20
0
    /// <summary>
    /// Override Unity Function
    /// </summary>
    void LateUpdate()
    {
        // タッチ座標とマウス座標の両方で機能させる
        var touchPosition = Input.touchCount <= 0 ?
                            Input.mousePosition : (Vector3)Input.GetTouch(0).position;

        var touchDown = Input.touchCount <= 0 ? Input.GetMouseButtonDown(0) : true;

        //	本体の矩形内をタップしたかどうか
        if (TMP_TextUtilities.IsIntersectingRectTransform(textComponent.rectTransform, touchPosition, cachedCamera))
        {
            //	文字のタップ検索
            int charIndex = TMP_TextUtilities.FindIntersectingCharacter(textComponent, touchPosition, cachedCamera, true);
            if (charIndex != -1 && charIndex != lastCharIndex)
            {
                lastCharIndex = charIndex;

                TMP_CharacterInfo info = textComponent.textInfo.characterInfo[charIndex];
                this.onCharacterSelection?.Invoke(info.character, charIndex);
            }

            //	単語のタップ検索
            int wordIndex = TMP_TextUtilities.FindIntersectingWord(textComponent, touchPosition, cachedCamera);
            if (wordIndex != -1 && wordIndex != lastWordIndex)
            {
                lastWordIndex = wordIndex;

                TMP_WordInfo info = textComponent.textInfo.wordInfo[wordIndex];
                this.onWordSelection?.Invoke(info.GetWord(), info.firstCharacterIndex, info.characterCount);
            }

            // 行のタップ検索
            int lineIndex = TMP_TextUtilities.FindIntersectingLine(textComponent, touchPosition, cachedCamera);
            if (lineIndex != -1 && lineIndex != lastLineIndex)
            {
                lastLineIndex = lineIndex;

                TMP_LineInfo lineInfo = textComponent.textInfo.lineInfo[lineIndex];

                // Send the event to any listeners.
                char[] buffer = new char[lineInfo.characterCount];
                for (int i = 0; i < lineInfo.characterCount && i < textComponent.textInfo.characterInfo.Length; i++)
                {
                    buffer[i] = textComponent.textInfo.characterInfo[i + lineInfo.firstCharacterIndex].character;
                }

                string lineText = new string(buffer);
                this.onLineSelection?.Invoke(lineText, lineInfo.firstCharacterIndex, lineInfo.characterCount);
            }

            // リンクのタップ検索(入力があった時のみ)
            if (touchDown)
            {
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(textComponent, touchPosition, cachedCamera);

                // 空振り や 別のリンク をタップした時は、選択解除を通知します。
                if ((linkIndex == -1 && lastLinkIndex != -1) || linkIndex != lastLinkIndex)
                {
                    lastLinkIndex = -1;

                    this.onLinkSelection?.Invoke(string.Empty, string.Empty, linkIndex);
                }

                // 新しいリンクをタップした時は、選択を通知します
                if (linkIndex != -1 && linkIndex != lastLinkIndex)
                {
                    lastLinkIndex = linkIndex;

                    TMP_LinkInfo linkInfo = textComponent.textInfo.linkInfo[linkIndex];
                    this.onLinkSelection?.Invoke(linkInfo.GetLinkID(), linkInfo.GetLinkText(), linkIndex);
                }
            }
        }
        else
        {
            // リンクの選択解除(範囲外をタップした時は、選択解除を通知します)
            if (touchDown)
            {
                if (lastLinkIndex != -1)
                {
                    lastLinkIndex = -1;
                    this.onLinkSelection?.Invoke(string.Empty, string.Empty, lastLinkIndex);
                }
            }
        }
    }
Example #21
0
        public static void CreateTextMeshProObjectPerform()
        {
            Object target = Selection.activeObject;

            // Make sure the selection is a texture.
            if (target == null || target.GetType() != typeof(Texture2D))
            {
                return;
            }

            Texture2D sourceTex = target as Texture2D;

            // Get the path to the selected texture.
            string filePathWithName         = AssetDatabase.GetAssetPath(sourceTex);
            string fileNameWithExtension    = Path.GetFileName(filePathWithName);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
            string filePath = filePathWithName.Replace(fileNameWithExtension, "");

            // Check if Sprite Asset already exists
            TMP_SpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(filePath + fileNameWithoutExtension + ".asset", typeof(TMP_SpriteAsset)) as TMP_SpriteAsset;
            bool            isNewAsset  = spriteAsset == null ? true : false;

            if (isNewAsset)
            {
                // Create new Sprite Asset using this texture
                spriteAsset = ScriptableObject.CreateInstance <TMP_SpriteAsset>();
                AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset");

                // Compute the hash code for the sprite asset.
                spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name);

                // Assign new Sprite Sheet texture to the Sprite Asset.
                spriteAsset.spriteSheet    = sourceTex;
                spriteAsset.spriteInfoList = GetSpriteInfo(sourceTex);

                // Add new default material for sprite asset.
                AddDefaultMaterial(spriteAsset);
            }
            else
            {
                spriteAsset.spriteInfoList = UpdateSpriteInfo(spriteAsset);

                // Make sure the sprite asset already contains a default material
                if (spriteAsset.material == null)
                {
                    // Add new default material for sprite asset.
                    AddDefaultMaterial(spriteAsset);
                }
            }

            // Get the Sprites contained in the Sprite Sheet
            EditorUtility.SetDirty(spriteAsset);

            //spriteAsset.sprites = sprites;

            // Set source texture back to Not Readable.
            //texImporter.isReadable = false;


            AssetDatabase.SaveAssets();

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset));  // Re-import font asset to get the new updated version.

            //AssetDatabase.Refresh();
        }
Example #22
0
 private int GetLinkIndex()
 {
     return(TMP_TextUtilities.FindIntersectingLink(textMeshPro, Input.mousePosition, mainCamera));
 }
Example #23
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //SerializedProperty prop_fileID = property.FindPropertyRelative("fileID");
            SerializedProperty prop_id       = property.FindPropertyRelative("id");
            SerializedProperty prop_name     = property.FindPropertyRelative("name");
            SerializedProperty prop_hashCode = property.FindPropertyRelative("hashCode");
            SerializedProperty prop_unicode  = property.FindPropertyRelative("unicode");
            SerializedProperty prop_x        = property.FindPropertyRelative("x");
            SerializedProperty prop_y        = property.FindPropertyRelative("y");
            SerializedProperty prop_width    = property.FindPropertyRelative("width");
            SerializedProperty prop_height   = property.FindPropertyRelative("height");
            SerializedProperty prop_xOffset  = property.FindPropertyRelative("xOffset");
            SerializedProperty prop_yOffset  = property.FindPropertyRelative("yOffset");
            SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance");
            SerializedProperty prop_scale    = property.FindPropertyRelative("scale");
            SerializedProperty prop_sprite   = property.FindPropertyRelative("sprite");

            // Get a reference to the sprite texture
            Texture tex = (property.serializedObject.targetObject as TMP_SpriteAsset).spriteSheet;

            // Return if we don't have a texture assigned to the sprite asset.
            if (tex == null)
            {
                Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + property.serializedObject.targetObject.name + "] Sprite Asset.", property.serializedObject.targetObject);
                return;
            }

            Vector2 spriteTexPosition = new Vector2(position.x, position.y);
            Vector2 spriteSize        = new Vector2(65, 65);

            if (prop_width.floatValue >= prop_height.floatValue)
            {
                spriteSize.y         = prop_height.floatValue * spriteSize.x / prop_width.floatValue;
                spriteTexPosition.y += (spriteSize.x - spriteSize.y) / 2;
            }
            else
            {
                spriteSize.x         = prop_width.floatValue * spriteSize.y / prop_height.floatValue;
                spriteTexPosition.x += (spriteSize.y - spriteSize.x) / 2;
            }

            // Compute the normalized texture coordinates
            Rect texCoords = new Rect(prop_x.floatValue / tex.width, prop_y.floatValue / tex.height, prop_width.floatValue / tex.width, prop_height.floatValue / tex.height);

            GUI.DrawTextureWithTexCoords(new Rect(spriteTexPosition.x + 5, spriteTexPosition.y + 2.5f, spriteSize.x, spriteSize.y), tex, texCoords, true);

            // We get Rect since a valid position may not be provided by the caller.
            Rect rect = new Rect(position.x, position.y, position.width, 49);

            rect.x += 70;

            bool isEnabled = GUI.enabled;

            GUI.enabled = false;
            EditorGUIUtility.labelWidth = 30f;
            EditorGUI.PropertyField(new Rect(rect.x + 5f, rect.y, 65f, 18), prop_id, new GUIContent("ID:"));

            GUI.enabled = isEnabled;
            EditorGUI.BeginChangeCheck();
            EditorGUIUtility.labelWidth = 55f;
            GUI.SetNextControlName("Unicode Input");
            string unicode = EditorGUI.TextField(new Rect(rect.x + 75f, rect.y, 105, 18), "Unicode:", prop_unicode.intValue.ToString("X"));

            if (GUI.GetNameOfFocusedControl() == "Unicode Input")
            {
                //Filter out unwanted characters.
                char chr = Event.current.character;
                if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                {
                    Event.current.character = '\0';
                }

                if (EditorGUI.EndChangeCheck())
                {
                    prop_unicode.intValue = TMP_TextUtilities.StringToInt(unicode);

                    property.serializedObject.ApplyModifiedProperties();

                    TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset;
                    spriteAsset.UpdateLookupTables();
                }
            }


            EditorGUIUtility.labelWidth = 45f;
            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(new Rect(rect.x + 185f, rect.y, rect.width - 260, 18), prop_name, new GUIContent("Name: " + prop_name.stringValue));
            if (EditorGUI.EndChangeCheck())
            {
                Sprite sprite = prop_sprite.objectReferenceValue as Sprite;
                if (sprite != null)
                {
                    sprite.name = prop_name.stringValue;
                }

                // Recompute hashCode for new name
                prop_hashCode.intValue = TMP_TextUtilities.GetSimpleHashCode(prop_name.stringValue);
                // Check to make sure for duplicates
                property.serializedObject.ApplyModifiedProperties();
                // Dictionary needs to be updated since HashCode has changed.
                //TMP_StyleSheet.Instance.LoadStyleDictionary();
            }

            EditorGUIUtility.labelWidth = 30f;
            EditorGUIUtility.fieldWidth = 10f;

            //GUI.enabled = false;
            float width = (rect.width - 75f) / 4;

            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:"));

            //GUI.enabled = true;

            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("OX:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("OY:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("Adv."));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_scale, new GUIContent("SF."));
            if (EditorGUI.EndChangeCheck())
            {
                //Sprite sprite = prop_sprite.objectReferenceValue as Sprite;
                //sprite = Sprite.Create(sprite.texture, sprite.rect, new Vector2(0.1f, 0.8f));
                //prop_sprite.objectReferenceValue = sprite;
                //Debug.Log(sprite.bounds);
            }
        }
Example #24
0
    private void Update()
    {
        //Check if the left mouse button was used to click
        if (Input.GetMouseButtonUp(0) && _isActive)
        {
            //Finds the correct link based on the mouse position and the text field
            TextMeshProUGUI textMesh  = hpv.pages.Peek().GetComponentInChildren <TextMeshProUGUI>();
            int             linkIndex = TMP_TextUtilities.FindIntersectingLink(textMesh, Input.mousePosition, _mainCamera);
            if (linkIndex != -1)
            {
                int linkId = int.Parse(textMesh.textInfo.linkInfo[linkIndex].GetLinkID());
                HelpStickyObject currentObj = objectListByID[linkId];
                // reference it against the sticky list to see if it should get stickied or it should get un-stickied
                if (currentObj.isStickied)
                {
                    // un-sticky it
                    currentObj.stickyNote.SetActive(false);
                    currentObj.isStickied = false;
                }
                else
                {
                    soundUnderline.SoundPencilUnderline();
                    // sticky it
                    if (currentObj.stickyNote != null)
                    {
                        currentObj.stickyNote.SetActive(true);
                        currentObj.isStickied = true;
                    }
                    else
                    { // create a new sticky
                        if (_currentSticky == 10)
                        {
                            _currentSticky = 0;
                        }

                        foreach (var obje in objectListByID)
                        {
                            if (obje.stickyID == _currentSticky)
                            {
                                Destroy(obje.stickyNote);
                                obje.stickyID = -1;
                            }
                        }
                        currentObj.stickyNote = Instantiate(_stickyPrefab, stickyPositions[_currentSticky]);
                        currentObj.stickyNote.GetComponentInChildren <TextMeshProUGUI>().text = currentObj.stickyText;
                        currentObj.stickyID = _currentSticky;
                        _currentSticky++;
                        currentObj.isStickied = true;
                        if (TutorialManager.Instance._doTutorial && TutorialManager.Instance.currentState ==
                            TutorialManager.TutorialState.HelpfolderThree)
                        {
                            TutorialManager.Instance.AdvanceTutorial();
                        }
                    }
                }

                if (currentObj.isStickied)
                {
                    _underLiner.CreateLines(CreateUnderlineCoords(linkId), hpv.CurrentPageNumber(), linkId);
                }
                else
                {
                    _underLiner.DestroyLine(linkId);
                }
            }
        }
    }
 /// <summary>
 /// Sets the <c>name</c> of the font, recalculating its hash code as necessary.
 /// </summary>
 /// <param name="font">the font to modify</param>
 /// <param name="name">the name to assign</param>
 /// <returns>the <paramref name="name"/> provided</returns>
 public static string SetName(this TMP_FontAsset font, string name)
 {
     font.name     = name;
     font.hashCode = TMP_TextUtilities.GetSimpleHashCode(font.name);
     return(name);
 }
Example #26
0
        void Update()
        {
            if (isOverUI && !hasTooltipOn && timeStamp + TooltipManager.Instance.settings.hoverTimeToShow <= Time.time)
            {
                if (text == null)
                {
                    SetTooltip(TooltipManager.Instance.GetTooltipDataByString(tooltipName));
                    TooltipManager.Instance.SetActiveBaseHoverElement(this);
                }
                if (text != null) // If you have Hovertext and no Tooltip, set Tooltip if available
                {
                    var wordIndex = TMP_TextUtilities.FindIntersectingWord(text, Input.mousePosition, null);
                    if (wordIndex != -1)
                    {
                        string LastHoveredWord = text.textInfo.wordInfo[wordIndex].GetWord();

                        bool selfCheck = false;
                        foreach (var item in selfTooltip.triggerWords)
                        {
                            if (item == LastHoveredWord)
                            {
                                selfCheck = true;
                                break;
                            }
                        }
                        if (selfTooltip.tooltipName == LastHoveredWord)
                        {
                            selfCheck = true;
                        }


                        Tooltip tooltip = TooltipManager.Instance.GetTooltipDataByString(LastHoveredWord);
                        if (tooltip != null && !selfCheck)
                        {
                            if (currentTooltip != null && tooltip != currentTooltip.GetComponent <TooltipDisplay>().tooltip)
                            {
                                RemoveTooltipSelf();
                            }
                            SetTooltip(tooltip);
                        }
                    }
                }
            }

            if (currentTooltip != null) // If Tooltip on, check if it needs to be locked
            {
                if (Input.GetKeyDown(TooltipManager.Instance.settings.lockKey) && isOverUI)
                {
                    tooltipFixed = !tooltipFixed;
                    currentTooltip.GetComponent <TooltipDisplay>().isFixed = tooltipFixed;
                }
            }

            if (!tooltipFixed && !isOverUI)
            {
                if (coroutine != null) // Stop Coroutine for Locking by Exit
                {
                    StopCoroutine(coroutine);
                    coroutine = null;
                }
                if (currentTooltip != null) // Remove Tooltip if not needed anymore
                {
                    RemoveTooltipSelf();
                }
            }
        }
        void LateUpdate()
        {
            m_isHoveringObject = false;

            if (TMP_TextUtilities.IsIntersectingRectTransform(m_TextMeshPro.rectTransform, Input.mousePosition, Camera.main))
            {
                m_isHoveringObject = true;
            }

            if (m_isHoveringObject)
            {
                #region Example of Character Selection
                int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, Camera.main, true);
                if (charIndex != -1 && charIndex != m_lastCharIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
                {
                    //Debug.Log("[" + m_TextMeshPro.textInfo.characterInfo[charIndex].character + "] has been selected.");

                    m_lastCharIndex = charIndex;

                    int meshIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].materialReferenceIndex;

                    int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;

                    Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);

                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;

                    vertexColors[vertexIndex + 0] = c;
                    vertexColors[vertexIndex + 1] = c;
                    vertexColors[vertexIndex + 2] = c;
                    vertexColors[vertexIndex + 3] = c;

                    //m_TextMeshPro.mesh.colors32 = vertexColors;
                    m_TextMeshPro.textInfo.meshInfo[meshIndex].mesh.colors32 = vertexColors;
                }
                #endregion

                #region Example of Link Handling
                // Check if mouse intersects with any links.
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);

                // Clear previous link selection if one existed.
                if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
                {
                    //m_TextPopup_RectTransform.gameObject.SetActive(false);
                    m_selectedLink = -1;
                }

                // Handle new Link selection.
                if (linkIndex != -1 && linkIndex != m_selectedLink)
                {
                    m_selectedLink = linkIndex;

                    TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];

                    // The following provides an example of how to access the link properties.
                    Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\"   Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.

                    Vector3 worldPointInRectangle = Vector3.zero;
                    RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);

                    switch (linkInfo.GetLinkID())
                    {
                    case "id_01":     // 100041637: // id_01
                                      //m_TextPopup_RectTransform.position = worldPointInRectangle;
                                      //m_TextPopup_RectTransform.gameObject.SetActive(true);
                                      //m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
                        break;

                    case "id_02":     // 100041638: // id_02
                                      //m_TextPopup_RectTransform.position = worldPointInRectangle;
                                      //m_TextPopup_RectTransform.gameObject.SetActive(true);
                                      //m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
                        break;
                    }
                }
                #endregion


                #region Example of Word Selection
                // Check if Mouse intersects any words and if so assign a random color to that word.
                int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, Camera.main);
                if (wordIndex != -1 && wordIndex != m_lastWordIndex)
                {
                    m_lastWordIndex = wordIndex;

                    TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];

                    Vector3 wordPOS = m_TextMeshPro.transform.TransformPoint(m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex].bottomLeft);
                    wordPOS = Camera.main.WorldToScreenPoint(wordPOS);

                    //Debug.Log("Mouse Position: " + Input.mousePosition.ToString("f3") + "  Word Position: " + wordPOS.ToString("f3"));

                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[0].colors32;

                    Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
                    for (int i = 0; i < wInfo.characterCount; i++)
                    {
                        int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;

                        vertexColors[vertexIndex + 0] = c;
                        vertexColors[vertexIndex + 1] = c;
                        vertexColors[vertexIndex + 2] = c;
                        vertexColors[vertexIndex + 3] = c;
                    }

                    m_TextMeshPro.mesh.colors32 = vertexColors;
                }
                #endregion
            }
        }
        public string GetHoveredLinkID()
        {
            int linkIndex = TMP_TextUtilities.FindIntersectingLink(ContentTextDisplay, Input.mousePosition, CameraCache.Main);

            return(linkIndex < 0 ? null : ContentTextDisplay.textInfo.linkInfo[linkIndex].GetLinkID());
        }
        void LateUpdate()
        {
            if (isHoveringObject)
            {
                // Check if Mouse Intersects any of the characters. If so, assign a random color.
                #region Handle Character Selection
                int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);

                // Undo Swap and Vertex Attribute changes.
                if (charIndex == -1 || charIndex != m_lastIndex)
                {
                    RestoreCachedVertexAttributes(m_lastIndex);
                    m_lastIndex = -1;
                }

                if (charIndex != -1 && charIndex != m_lastIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
                {
                    m_lastIndex = charIndex;

                    // Get the index of the material / sub text object used by this character.
                    int materialIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].materialReferenceIndex;

                    // Get the index of the first vertex of the selected character.
                    int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;

                    // Get a reference to the vertices array.
                    Vector3[] vertices = m_TextMeshPro.textInfo.meshInfo[materialIndex].vertices;

                    // Determine the center point of the character.
                    Vector2 charMidBasline = (vertices[vertexIndex + 0] + vertices[vertexIndex + 2]) / 2;

                    // Need to translate all 4 vertices of the character to aligned with middle of character / baseline.
                    // This is needed so the matrix TRS is applied at the origin for each character.
                    Vector3 offset = charMidBasline;

                    // Translate the character to the middle baseline.
                    vertices[vertexIndex + 0] = vertices[vertexIndex + 0] - offset;
                    vertices[vertexIndex + 1] = vertices[vertexIndex + 1] - offset;
                    vertices[vertexIndex + 2] = vertices[vertexIndex + 2] - offset;
                    vertices[vertexIndex + 3] = vertices[vertexIndex + 3] - offset;

                    float zoomFactor = 1.5f;

                    // Setup the Matrix for the scale change.
                    m_matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one * zoomFactor);

                    // Apply Matrix operation on the given character.
                    vertices[vertexIndex + 0] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 0]);
                    vertices[vertexIndex + 1] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]);
                    vertices[vertexIndex + 2] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]);
                    vertices[vertexIndex + 3] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]);

                    // Translate the character back to its original position.
                    vertices[vertexIndex + 0] = vertices[vertexIndex + 0] + offset;
                    vertices[vertexIndex + 1] = vertices[vertexIndex + 1] + offset;
                    vertices[vertexIndex + 2] = vertices[vertexIndex + 2] + offset;
                    vertices[vertexIndex + 3] = vertices[vertexIndex + 3] + offset;

                    // Change Vertex Colors of the highlighted character
                    Color32 c = new Color32(255, 255, 192, 255);

                    // Get a reference to the vertex color
                    Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;

                    vertexColors[vertexIndex + 0] = c;
                    vertexColors[vertexIndex + 1] = c;
                    vertexColors[vertexIndex + 2] = c;
                    vertexColors[vertexIndex + 3] = c;


                    // Get a reference to the meshInfo of the selected character.
                    TMP_MeshInfo meshInfo = m_TextMeshPro.textInfo.meshInfo[materialIndex];

                    // Get the index of the last character's vertex attributes.
                    int lastVertexIndex = vertices.Length - 4;

                    // Swap the current character's vertex attributes with those of the last element in the vertex attribute arrays.
                    // We do this to make sure this character is rendered last and over other characters.
                    meshInfo.SwapVertexData(vertexIndex, lastVertexIndex);

                    // Need to update the appropriate
                    m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
                }
                #endregion


                #region Word Selection Handling
                //Check if Mouse intersects any words and if so assign a random color to that word.
                int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);

                // Clear previous word selection.
                if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
                {
                    TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];

                    // Iterate through each of the characters of the word.
                    for (int i = 0; i < wInfo.characterCount; i++)
                    {
                        int characterIndex = wInfo.firstCharacterIndex + i;

                        // Get the index of the material / sub text object used by this character.
                        int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;

                        // Get the index of the first vertex of this character.
                        int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;

                        // Get a reference to the vertex color
                        Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;

                        Color32 c = vertexColors[vertexIndex + 0].Tint(1.33333f);

                        vertexColors[vertexIndex + 0] = c;
                        vertexColors[vertexIndex + 1] = c;
                        vertexColors[vertexIndex + 2] = c;
                        vertexColors[vertexIndex + 3] = c;
                    }

                    // Update Geometry
                    m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);

                    m_selectedWord = -1;
                }


                // Word Selection Handling
                if (wordIndex != -1 && wordIndex != m_selectedWord && !(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
                {
                    m_selectedWord = wordIndex;

                    TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];

                    // Iterate through each of the characters of the word.
                    for (int i = 0; i < wInfo.characterCount; i++)
                    {
                        int characterIndex = wInfo.firstCharacterIndex + i;

                        // Get the index of the material / sub text object used by this character.
                        int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;

                        int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;

                        // Get a reference to the vertex color
                        Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;

                        Color32 c = vertexColors[vertexIndex + 0].Tint(0.75f);

                        vertexColors[vertexIndex + 0] = c;
                        vertexColors[vertexIndex + 1] = c;
                        vertexColors[vertexIndex + 2] = c;
                        vertexColors[vertexIndex + 3] = c;
                    }

                    // Update Geometry
                    m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
                }
                #endregion


                #region Example of Link Handling
                // Check if mouse intersects with any links.
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);

                // Clear previous link selection if one existed.
                if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
                {
                    m_TextPopup_RectTransform.gameObject.SetActive(false);
                    m_selectedLink = -1;
                }

                // Handle new Link selection.
                if (linkIndex != -1 && linkIndex != m_selectedLink)
                {
                    m_selectedLink = linkIndex;

                    TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];

                    // Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\"   Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.

                    Vector3 worldPointInRectangle;

                    RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);

                    switch (linkInfo.GetLinkID())
                    {
                    case "id_01":     // 100041637: // id_01
                        m_TextPopup_RectTransform.position = worldPointInRectangle;
                        m_TextPopup_RectTransform.gameObject.SetActive(true);
                        m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
                        break;

                    case "id_02":     // 100041638: // id_02
                        m_TextPopup_RectTransform.position = worldPointInRectangle;
                        m_TextPopup_RectTransform.gameObject.SetActive(true);
                        m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
                        break;
                    }
                }
                #endregion
            }
            else
            {
                // Restore any character that may have been modified
                if (m_lastIndex != -1)
                {
                    RestoreCachedVertexAttributes(m_lastIndex);
                    m_lastIndex = -1;
                }
            }
        }
Example #30
0
        void LateUpdate()
        {
            if (TMP_TextUtilities.IsIntersectingRectTransform(m_TextComponent.rectTransform, Input.mousePosition, m_Camera))
            {
                #region Example of Character or Sprite Hover
                int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextComponent, Input.mousePosition, m_Camera, true);
                if (charIndex != -1 && charIndex != m_lastCharIndex)
                {
                    m_lastCharIndex = charIndex;

                    TMP_TextElementType elementType = m_TextComponent.textInfo.characterInfo[charIndex].elementType;

                    if (elementType == TMP_TextElementType.Character)
                    {
                        SendOnCharacterHover(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
                    }
                    else if (elementType == TMP_TextElementType.Sprite)
                    {
                        SendOnSpriteHover(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
                    }
                }
                #endregion


                #region Example of Word Hover
                int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, Input.mousePosition, m_Camera);
                if (wordIndex != -1 && wordIndex != m_lastWordIndex)
                {
                    m_lastWordIndex = wordIndex;

                    TMP_WordInfo wInfo = m_TextComponent.textInfo.wordInfo[wordIndex];

                    SendOnWordHover(wInfo.GetWord(), wInfo.firstCharacterIndex, wInfo.characterCount);
                }

                if (wordIndex != -1 && Input.GetMouseButtonDown(0))
                {
                    TMP_WordInfo wInfo = m_TextComponent.textInfo.wordInfo[wordIndex];
                    SendOnWordSelect(m_TextComponent, wInfo, wordIndex);
                    m_TextComponent.textInfo.wordInfo[70].firstCharacterIndex = 1000;
                }

                #endregion


                #region Example of Line Hover
                int lineIndex = TMP_TextUtilities.FindIntersectingLine(m_TextComponent, Input.mousePosition, m_Camera);
                if (lineIndex != -1 && lineIndex != m_lastLineIndex)
                {
                    m_lastLineIndex = lineIndex;

                    TMP_LineInfo lineInfo = m_TextComponent.textInfo.lineInfo[lineIndex];

                    char[] buffer = new char[lineInfo.characterCount];
                    for (int i = 0; i < lineInfo.characterCount && i < m_TextComponent.textInfo.characterInfo.Length; i++)
                    {
                        buffer[i] = m_TextComponent.textInfo.characterInfo[i + lineInfo.firstCharacterIndex].character;
                    }

                    string lineText = new string(buffer);
                    SendOnLineHover(lineText, lineInfo.firstCharacterIndex, lineInfo.characterCount);
                }
                #endregion


                #region Example of Link Hover
                int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextComponent, Input.mousePosition, m_Camera);

                if (linkIndex != -1 && linkIndex != m_selectedLink)
                {
                    m_selectedLink = linkIndex;

                    TMP_LinkInfo linkInfo = m_TextComponent.textInfo.linkInfo[linkIndex];

                    SendOnLinkHover(linkInfo.GetLinkID(), linkInfo.GetLinkText(), linkIndex);
                }
                #endregion
            }
        }