EnumControl.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // ReSharper disable once RedundantUsingDirective
  2. using System.Reflection;
  3. namespace SRDebugger.UI.Controls.Data
  4. {
  5. using System;
  6. using SRF;
  7. using SRF.UI;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. public class EnumControl : DataBoundControl
  11. {
  12. private object _lastValue;
  13. private string[] _names;
  14. private Array _values;
  15. [RequiredField] public LayoutElement ContentLayoutElement;
  16. public GameObject[] DisableOnReadOnly;
  17. [RequiredField] public SRSpinner Spinner;
  18. [RequiredField] public Text Title;
  19. [RequiredField] public Text Value;
  20. protected override void Start()
  21. {
  22. base.Start();
  23. }
  24. protected override void OnBind(string propertyName, Type t)
  25. {
  26. base.OnBind(propertyName, t);
  27. Title.text = propertyName;
  28. Spinner.interactable = !IsReadOnly;
  29. if (DisableOnReadOnly != null)
  30. {
  31. foreach (var child in DisableOnReadOnly)
  32. {
  33. child.SetActive(!IsReadOnly);
  34. }
  35. }
  36. _names = Enum.GetNames(t);
  37. _values = Enum.GetValues(t);
  38. var longestName = "";
  39. for (var i = 0; i < _names.Length; i++)
  40. {
  41. if (_names[i].Length > longestName.Length)
  42. {
  43. longestName = _names[i];
  44. }
  45. }
  46. if (_names.Length == 0)
  47. {
  48. return;
  49. }
  50. // Set preferred width of content to the largest possible value size
  51. var width = Value.cachedTextGeneratorForLayout.GetPreferredWidth(longestName,
  52. Value.GetGenerationSettings(new Vector2(float.MaxValue, Value.preferredHeight)));
  53. ContentLayoutElement.preferredWidth = width;
  54. }
  55. protected override void OnValueUpdated(object newValue)
  56. {
  57. _lastValue = newValue;
  58. Value.text = newValue.ToString();
  59. LayoutRebuilder.MarkLayoutForRebuild(GetComponent<RectTransform>());
  60. }
  61. public override bool CanBind(Type type, bool isReadOnly)
  62. {
  63. #if NETFX_CORE
  64. return type.GetTypeInfo().IsEnum;
  65. #else
  66. return type.IsEnum;
  67. #endif
  68. }
  69. private void SetIndex(int i)
  70. {
  71. UpdateValue(_values.GetValue(i));
  72. Refresh();
  73. }
  74. public void GoToNext()
  75. {
  76. var currentIndex = Array.IndexOf(_values, _lastValue);
  77. SetIndex(SRMath.Wrap(_values.Length, currentIndex + 1));
  78. }
  79. public void GoToPrevious()
  80. {
  81. var currentIndex = Array.IndexOf(_values, _lastValue);
  82. SetIndex(SRMath.Wrap(_values.Length, currentIndex - 1));
  83. }
  84. }
  85. }