359 lines
12 KiB
C#
359 lines
12 KiB
C#
#nullable enable
|
|
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// Double 실수(64비트 배정밀도) 입력 필드 컴포넌트.
|
|
/// Unity DoubleField를 래핑하여 커스텀 스타일을 적용합니다.
|
|
/// float보다 높은 정밀도의 소수점 숫자를 입력받습니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>double(배정밀도 실수)란?</b></para>
|
|
/// <para>double은 64비트 배정밀도 부동소수점 타입으로, float보다 더 정밀한 소수를 저장합니다.</para>
|
|
/// <list type="bullet">
|
|
/// <item><description>과학 계산, 금융 데이터, 정밀 측정값에 사용</description></item>
|
|
/// <item><description>float보다 약 2배 정밀도 (유효숫자 15-17자리)</description></item>
|
|
/// <item><description>일반 게임 로직에는 UTKFloatField로 충분</description></item>
|
|
/// <item><description>Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출)</description></item>
|
|
/// <item><description>에러 상태 시 붉은 외곽선 + 에러 메시지 표시</description></item>
|
|
/// </list>
|
|
/// <para><b>float vs double:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description>float: 32비트, 유효숫자 6-9자리, 게임 그래픽에 적합</description></item>
|
|
/// <item><description>double: 64비트, 유효숫자 15-17자리, 정밀 계산에 적합</description></item>
|
|
/// </list>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 기본 Double 필드 생성
|
|
/// var doubleField = new UTKDoubleField();
|
|
/// doubleField.label = "정밀 좌표";
|
|
/// doubleField.Value = 3.141592653589793;
|
|
///
|
|
/// // 값 변경 이벤트
|
|
/// doubleField.OnValueChanged += (value) => {
|
|
/// Debug.Log($"값: {value:F15}"); // 소수점 15자리 출력
|
|
/// };
|
|
///
|
|
/// // 라벨과 기본값을 지정하는 생성자
|
|
/// var latitudeField = new UTKDoubleField("위도", 37.5665);
|
|
///
|
|
/// // 현재 값 읽기/쓰기
|
|
/// double currentValue = doubleField.Value;
|
|
/// doubleField.Value = 127.9780;
|
|
/// </code>
|
|
/// <para><b>Validation (입력 검증):</b></para>
|
|
/// <code>
|
|
/// // 검증 함수 설정 (Func<bool>)
|
|
/// var precisionField = new UTKDoubleField("정밀 값", 0);
|
|
/// precisionField.ErrorMessage = "값은 0보다 커야 합니다.";
|
|
/// precisionField.Validation = () => precisionField.Value > 0;
|
|
/// // → FocusOut 시 자동으로 검증
|
|
///
|
|
/// // 강제 검증 호출
|
|
/// bool isValid = precisionField.Validate();
|
|
///
|
|
/// // 에러 수동 해제
|
|
/// precisionField.ClearError();
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code><![CDATA[
|
|
/// <!-- 기본 Double 필드 -->
|
|
/// <utk:UTKDoubleField label="경도" value="127.9780" />
|
|
///
|
|
/// <!-- 비활성화 상태 -->
|
|
/// <utk:UTKDoubleField label="PI" value="3.141592653589793" is-enabled="false" />
|
|
///
|
|
/// <!-- label min-width 설정 -->
|
|
/// <utk:UTKDoubleField label="경도" label-min-width="120" />
|
|
/// ]]></code>
|
|
/// <para><b>Label Min-Width 설정:</b></para>
|
|
/// <code>
|
|
/// // label이 있을 때 .unity-label의 min-width를 설정
|
|
/// var doubleField = new UTKDoubleField("경도");
|
|
/// doubleField.LabelMinWidth = 120f; // 120px
|
|
/// </code>
|
|
/// <para><b>실제 활용 예시 (GPS 좌표):</b></para>
|
|
/// <code>
|
|
/// // GPS 좌표 입력 (높은 정밀도 필요)
|
|
/// var latField = new UTKDoubleField("위도 (Latitude)", gpsData.Latitude);
|
|
/// var lonField = new UTKDoubleField("경도 (Longitude)", gpsData.Longitude);
|
|
///
|
|
/// latField.OnValueChanged += (lat) => gpsData.Latitude = lat;
|
|
/// lonField.OnValueChanged += (lon) => gpsData.Longitude = lon;
|
|
/// </code>
|
|
/// </example>
|
|
[UxmlElement]
|
|
public partial class UTKDoubleField : DoubleField, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Input/UTKDoubleField";
|
|
#endregion
|
|
|
|
#region Fields
|
|
private bool _disposed;
|
|
private bool _isEnabled = true;
|
|
private string _errorMessage = "";
|
|
private float _labelMinWidth = -1f;
|
|
private Func<bool>? _validation;
|
|
private Label? _errorLabel;
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>값 변경 이벤트</summary>
|
|
public event Action<double>? OnValueChanged;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>현재 값</summary>
|
|
public double Value
|
|
{
|
|
get => value;
|
|
set => this.value = value;
|
|
}
|
|
|
|
/// <summary>에러 메시지. 비어있지 않으면 에러 상태로 표시</summary>
|
|
[UxmlAttribute("error-message")]
|
|
public string ErrorMessage
|
|
{
|
|
get => _errorMessage;
|
|
set
|
|
{
|
|
_errorMessage = value;
|
|
var hasError = !string.IsNullOrEmpty(value);
|
|
EnableInClassList("utk-double-field--error", hasError);
|
|
UpdateErrorLabel(hasError ? value : null);
|
|
}
|
|
}
|
|
|
|
/// <summary>검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시</summary>
|
|
public Func<bool>? Validation
|
|
{
|
|
get => _validation;
|
|
set => _validation = value;
|
|
}
|
|
|
|
/// <summary>활성화 상태</summary>
|
|
[UxmlAttribute("is-enabled")]
|
|
public bool IsEnabled
|
|
{
|
|
get => _isEnabled;
|
|
set
|
|
{
|
|
_isEnabled = value;
|
|
SetEnabled(value);
|
|
EnableInClassList("utk-double-field--disabled", !value);
|
|
}
|
|
}
|
|
|
|
/// <summary>label이 있을 때 .unity-label의 min-width (px). -1이면 미설정</summary>
|
|
[UxmlAttribute("label-min-width")]
|
|
public float LabelMinWidth
|
|
{
|
|
get => _labelMinWidth;
|
|
set
|
|
{
|
|
_labelMinWidth = value;
|
|
ApplyLabelMinWidth();
|
|
}
|
|
}
|
|
|
|
/// <summary>읽기 전용</summary>
|
|
public new bool isReadOnly
|
|
{
|
|
get => base.isReadOnly;
|
|
set
|
|
{
|
|
base.isReadOnly = value;
|
|
EnableInClassList("utk-double-field--readonly", value);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Constructor
|
|
public UTKDoubleField() : base()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
}
|
|
|
|
SetupStyles();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
}
|
|
|
|
public UTKDoubleField(string label, double defaultValue = 0) : this()
|
|
{
|
|
this.label = label;
|
|
value = defaultValue;
|
|
}
|
|
#endregion
|
|
|
|
#region Setup
|
|
private void SetupStyles()
|
|
{
|
|
AddToClassList("utk-double-field");
|
|
|
|
// label 설정 후 LabelMinWidth 적용
|
|
schedule.Execute(() => ApplyLabelMinWidth());
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
RegisterCallback<ChangeEvent<double>>(OnFieldValueChanged);
|
|
RegisterCallback<FocusOutEvent>(OnFocusOut);
|
|
RegisterCallback<KeyDownEvent>(OnKeyDown, TrickleDown.TrickleDown);
|
|
}
|
|
|
|
private void SubscribeToThemeChanges()
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
RegisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
}
|
|
|
|
private void OnAttachToPanelForTheme(AttachToPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
|
|
private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
}
|
|
|
|
private void OnThemeChanged(UTKTheme theme)
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
|
|
private void ApplyLabelMinWidth()
|
|
{
|
|
if (string.IsNullOrEmpty(label)) return;
|
|
var labelElement = this.Q<Label>(className: "unity-label");
|
|
if (labelElement == null) return;
|
|
|
|
if (_labelMinWidth >= 0)
|
|
{
|
|
labelElement.style.minWidth = _labelMinWidth;
|
|
}
|
|
else
|
|
{
|
|
labelElement.style.minWidth = StyleKeyword.Null;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Event Handlers
|
|
private void OnFieldValueChanged(ChangeEvent<double> evt)
|
|
{
|
|
OnValueChanged?.Invoke(evt.newValue);
|
|
}
|
|
|
|
private void OnFocusOut(FocusOutEvent evt)
|
|
{
|
|
RunValidation();
|
|
}
|
|
|
|
private void OnKeyDown(KeyDownEvent evt)
|
|
{
|
|
if (evt.keyCode == KeyCode.Return)
|
|
{
|
|
RunValidation();
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
/// <summary>
|
|
/// 강제로 Validation을 실행하여 에러 상태를 업데이트합니다.
|
|
/// </summary>
|
|
/// <returns>Validation이 null이면 true, 아니면 Validation 결과</returns>
|
|
public bool Validate()
|
|
{
|
|
return RunValidation();
|
|
}
|
|
|
|
/// <summary>에러 상태를 수동으로 해제합니다.</summary>
|
|
public void ClearError()
|
|
{
|
|
ErrorMessage = "";
|
|
}
|
|
|
|
private bool RunValidation()
|
|
{
|
|
if (_validation == null) return true;
|
|
|
|
var isValid = _validation.Invoke();
|
|
if (isValid)
|
|
{
|
|
// 검증 통과 시 에러 상태 해제
|
|
EnableInClassList("utk-double-field--error", false);
|
|
UpdateErrorLabel(null);
|
|
}
|
|
else
|
|
{
|
|
// 검증 실패 시 에러 상태 표시
|
|
EnableInClassList("utk-double-field--error", true);
|
|
UpdateErrorLabel(_errorMessage);
|
|
}
|
|
return isValid;
|
|
}
|
|
|
|
private void UpdateErrorLabel(string? message)
|
|
{
|
|
if (string.IsNullOrEmpty(message))
|
|
{
|
|
// 에러 라벨 숨기기 (존재하면)
|
|
if (_errorLabel != null)
|
|
{
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 에러 라벨 생성 (지연 생성 - 필요할 때만)
|
|
if (_errorLabel == null)
|
|
{
|
|
_errorLabel = new Label();
|
|
_errorLabel.AddToClassList("utk-double-field__error-message");
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
Add(_errorLabel);
|
|
}
|
|
|
|
_errorLabel.text = message;
|
|
_errorLabel.style.display = DisplayStyle.Flex;
|
|
}
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
UnregisterCallback<ChangeEvent<double>>(OnFieldValueChanged);
|
|
UnregisterCallback<FocusOutEvent>(OnFocusOut);
|
|
UnregisterCallback<KeyDownEvent>(OnKeyDown);
|
|
OnValueChanged = null;
|
|
_validation = null;
|
|
_errorLabel = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|