ObjectExtensions.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using XUnity.AutoTranslator.Plugin.Core.Configuration;
  7. using UnityEngine.UI;
  8. using XUnity.AutoTranslator.Plugin.Core.Constants;
  9. using XUnity.AutoTranslator.Plugin.Core.Utilities;
  10. namespace XUnity.AutoTranslator.Plugin.Core.Extensions
  11. {
  12. public static class ObjectExtensions
  13. {
  14. private static readonly object Sync = new object();
  15. private static readonly WeakDictionary<object, object> DynamicFields = new WeakDictionary<object, object>();
  16. public static bool SupportsStabilization( this object ui )
  17. {
  18. if( ui == null ) return false;
  19. var type = ui.GetType();
  20. return ui is Text
  21. || ( Types.UILabel != null && Types.UILabel.IsAssignableFrom( type ) )
  22. || ( Types.TMP_Text != null && Types.TMP_Text.IsAssignableFrom( type ) );
  23. }
  24. public static bool SupportsRichText( this object ui )
  25. {
  26. if( ui == null ) return false;
  27. var type = ui.GetType();
  28. return ( ui as Text )?.supportRichText == true
  29. || ( Types.AdvCommand != null && Types.AdvCommand.IsAssignableFrom( type ) );
  30. }
  31. public static TranslationInfo GetTranslationInfo( this object obj, bool isAwakening )
  32. {
  33. if( !Settings.EnableObjectTracking ) return null;
  34. if( !obj.SupportsStabilization() ) return null;
  35. var info = obj.Get<TranslationInfo>();
  36. info.IsAwake = info.IsAwake || isAwakening;
  37. return info;
  38. }
  39. public static T Get<T>( this object obj )
  40. where T : new()
  41. {
  42. lock( Sync )
  43. {
  44. if( DynamicFields.TryGetValue( obj, out object value ) )
  45. {
  46. return (T)value;
  47. }
  48. else
  49. {
  50. var t = new T();
  51. DynamicFields[ obj ] = t;
  52. return t;
  53. }
  54. }
  55. }
  56. public static void Cull()
  57. {
  58. lock( Sync )
  59. {
  60. DynamicFields.RemoveCollectedEntries();
  61. }
  62. }
  63. public static List<KeyValuePair<object, object>> GetAllRegisteredObjects()
  64. {
  65. lock( Sync )
  66. {
  67. return DynamicFields.ToList();
  68. }
  69. }
  70. public static void Remove( object obj )
  71. {
  72. lock( Sync )
  73. {
  74. DynamicFields.Remove( obj );
  75. }
  76. }
  77. }
  78. }