BITKit/Packages/Editor/StringHelper.cs

72 lines
2.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor;
using UnityEditor.UIElements;
using System.Text;
namespace BITKit.Editors
{
public class StringHelper : EditorWindow
{
[MenuItem("Tools/Open StringHelper")]
public static void Open()
{
var windows = GetWindow<StringHelper>();
windows.Show();
windows.titleContent = new GUIContent(nameof(StringHelper));
}
public void CreateGUI()
{
TextField textField = new("String");
IntegerField textPaddingLimit = new("TextPaddingLimit");
IntegerField textLengthLabel = new("TextLength");
IntegerField byteCountLabel = new("ByteCount");
IntegerField resultByteCount = new("ResultByteCount");
ProgressBar byteProgressBar = new();
ProgressBar paddingLimitBar = new();
Label formatString = new();
byteProgressBar.highValue = paddingLimitBar.highValue = 100;
byteProgressBar.lowValue = paddingLimitBar.lowValue = 0;
textField.RegisterValueChangedCallback(x => OnValueChanged(x.newValue));
textPaddingLimit.RegisterValueChangedCallback(x => OnValueChanged(textField.text));
textLengthLabel.isReadOnly = true;
byteCountLabel.isReadOnly = true;
rootVisualElement.Add(textField);
rootVisualElement.Add(textPaddingLimit);
rootVisualElement.Add(textLengthLabel);
rootVisualElement.Add(byteCountLabel);
rootVisualElement.Add(formatString);
rootVisualElement.Add(resultByteCount);
rootVisualElement.Add(paddingLimitBar);
rootVisualElement.Add(byteProgressBar);
void OnValueChanged(string value)
{
int byteCount = Encoding.UTF8.GetByteCount(value);
textLengthLabel.SetValueWithoutNotify(value.Length);
byteCountLabel.SetValueWithoutNotify(byteCount);
byteProgressBar.SetValueWithoutNotify(byteCount);
paddingLimitBar.SetValueWithoutNotify(textPaddingLimit.value);
formatString.text = Padding(value);
}
string Padding(string value)
{
int byteCount = Encoding.UTF8.GetByteCount(value);
var length = Mathf.Max(0, textPaddingLimit.value - byteCount);
value = value + new string('x', length) + ":END";
resultByteCount.SetValueWithoutNotify(Encoding.UTF8.GetByteCount(value));
return value;
}
}
}
}