TypeTable.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. #if UNITY_EDITOR
  6. using System.ComponentModel;
  7. #endif
  8. namespace UnityEngine.InputSystem.Utilities
  9. {
  10. /// <summary>
  11. /// A table mapping names to types in a case-insensitive mapping.
  12. /// </summary>
  13. internal struct TypeTable
  14. {
  15. public Dictionary<InternedString, Type> table;
  16. public IEnumerable<string> names => table.Keys.Select(x => x.ToString());
  17. public IEnumerable<InternedString> internedNames => table.Keys;
  18. // In the editor, we want to keep track of when the same type gets registered multiple times
  19. // with different names so that we can keep the aliases out of the UI.
  20. #if UNITY_EDITOR
  21. public HashSet<InternedString> aliases;
  22. #endif
  23. public void Initialize()
  24. {
  25. table = new Dictionary<InternedString, Type>();
  26. #if UNITY_EDITOR
  27. aliases = new HashSet<InternedString>();
  28. #endif
  29. }
  30. public InternedString FindNameForType(Type type)
  31. {
  32. if (type == null)
  33. throw new ArgumentNullException(nameof(type));
  34. foreach (var pair in table)
  35. if (pair.Value == type)
  36. return pair.Key;
  37. return new InternedString();
  38. }
  39. public void AddTypeRegistration(string name, Type type)
  40. {
  41. if (string.IsNullOrEmpty(name))
  42. throw new ArgumentException("Name cannot be null or empty", nameof(name));
  43. if (type == null)
  44. throw new ArgumentNullException(nameof(type));
  45. var internedName = new InternedString(name);
  46. #if UNITY_EDITOR
  47. if (table.ContainsValue(type))
  48. aliases.Add(internedName);
  49. #endif
  50. table[internedName] = type;
  51. }
  52. public Type LookupTypeRegistration(string name)
  53. {
  54. if (string.IsNullOrEmpty(name))
  55. throw new ArgumentException("Name cannot be null or empty", nameof(name));
  56. var internedName = new InternedString(name);
  57. if (table.TryGetValue(internedName, out var type))
  58. return type;
  59. return null;
  60. }
  61. #if UNITY_EDITOR
  62. public bool ShouldHideInUI(string name)
  63. {
  64. // Always hide aliases.
  65. if (aliases.Contains(new InternedString(name)))
  66. return true;
  67. // Hide entries that have [DesignTimeVisible(false)] on the type.
  68. var type = LookupTypeRegistration(name);
  69. var attribute = type?.GetCustomAttribute<DesignTimeVisibleAttribute>();
  70. return !(attribute?.Visible ?? true);
  71. }
  72. #endif
  73. }
  74. }