TextHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace XUnity.AutoTranslator.Plugin.Core.Utilities
  6. {
  7. public static class TextHelper
  8. {
  9. private static readonly Dictionary<string, Func<string, bool>> LanguageSymbolChecks = new Dictionary<string, Func<string, bool>>( StringComparer.OrdinalIgnoreCase )
  10. {
  11. { "ja", ContainsJapaneseSymbols },
  12. { "ja-JP", ContainsJapaneseSymbols },
  13. };
  14. public static Func<string, bool> GetSymbolCheck( string language )
  15. {
  16. if( LanguageSymbolChecks.TryGetValue( language, out Func<string, bool> check ) )
  17. {
  18. return check;
  19. }
  20. return text => true;
  21. }
  22. public static bool ContainsJapaneseSymbols( string text )
  23. {
  24. // Unicode Kanji Table:
  25. // http://www.rikai.com/library/kanjitables/kanji_codes.unicode.shtml
  26. foreach( var c in text )
  27. {
  28. if( ( c >= '\u3021' && c <= '\u3029' ) // kana-like symbols
  29. || ( c >= '\u3031' && c <= '\u3035' ) // kana-like symbols
  30. || ( c >= '\u3041' && c <= '\u3096' ) // hiragana
  31. || ( c >= '\u30a1' && c <= '\u30fa' ) // katakana
  32. || ( c >= '\uff66' && c <= '\uff9d' ) // half-width katakana
  33. || ( c >= '\u4e00' && c <= '\u9faf' ) // CJK unifed ideographs - Common and uncommon kanji
  34. || ( c >= '\u3400' && c <= '\u4db5' ) ) // CJK unified ideographs Extension A - Rare kanji ( 3400 - 4dbf)
  35. {
  36. return true;
  37. }
  38. }
  39. return false;
  40. }
  41. /// <summary>
  42. /// Decodes a text from a single-line serializable format.
  43. ///
  44. /// Shamelessly stolen from original translation plugin.
  45. /// </summary>
  46. public static string Decode( string text )
  47. {
  48. return text.Replace( "\\r", "\r" )
  49. .Replace( "\\n", "\n" )
  50. .Replace( "%3D", "=" );
  51. }
  52. /// <summary>
  53. /// Encodes a text into a single-line serializable format.
  54. ///
  55. /// Shamelessly stolen from original translation plugin.
  56. /// </summary>
  57. public static string Encode( string text )
  58. {
  59. return text.Replace( "\r", "\\r" )
  60. .Replace( "\n", "\\n" )
  61. .Replace( "=", "%3D" );
  62. }
  63. }
  64. }