SpanishAccentSystem.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Text;
  2. using Content.Server.Speech.Components;
  3. namespace Content.Server.Speech.EntitySystems
  4. {
  5. public sealed class SpanishAccentSystem : EntitySystem
  6. {
  7. public override void Initialize()
  8. {
  9. SubscribeLocalEvent<SpanishAccentComponent, AccentGetEvent>(OnAccent);
  10. }
  11. public string Accentuate(string message)
  12. {
  13. // Insert E before every S
  14. message = InsertS(message);
  15. // If a sentence ends with ?, insert a reverse ? at the beginning of the sentence
  16. message = ReplacePunctuation(message);
  17. return message;
  18. }
  19. private string InsertS(string message)
  20. {
  21. // Replace every new Word that starts with s/S
  22. var msg = message.Replace(" s", " es").Replace(" S", " Es");
  23. // Still need to check if the beginning of the message starts
  24. if (msg.StartsWith("s", StringComparison.Ordinal))
  25. {
  26. return msg.Remove(0, 1).Insert(0, "es");
  27. }
  28. else if (msg.StartsWith("S", StringComparison.Ordinal))
  29. {
  30. return msg.Remove(0, 1).Insert(0, "Es");
  31. }
  32. return msg;
  33. }
  34. private string ReplacePunctuation(string message)
  35. {
  36. var sentences = AccentSystem.SentenceRegex.Split(message);
  37. var msg = new StringBuilder();
  38. foreach (var s in sentences)
  39. {
  40. var toInsert = new StringBuilder();
  41. for (var i = s.Length - 1; i >= 0 && "?!‽".Contains(s[i]); i--)
  42. {
  43. toInsert.Append(s[i] switch
  44. {
  45. '?' => '¿',
  46. '!' => '¡',
  47. '‽' => '⸘',
  48. _ => ' '
  49. });
  50. }
  51. if (toInsert.Length == 0)
  52. {
  53. msg.Append(s);
  54. } else
  55. {
  56. msg.Append(s.Insert(s.Length - s.TrimStart().Length, toInsert.ToString()));
  57. }
  58. }
  59. return msg.ToString();
  60. }
  61. private void OnAccent(EntityUid uid, SpanishAccentComponent component, AccentGetEvent args)
  62. {
  63. args.Message = Accentuate(args.Message);
  64. }
  65. }
  66. }