SoftwareKeyboardApplet.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.HLE.HOS.Applets.SoftwareKeyboard;
  3. using Ryujinx.HLE.HOS.Services.Am.AppletAE;
  4. using System;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. namespace Ryujinx.HLE.HOS.Applets
  9. {
  10. internal class SoftwareKeyboardApplet : IApplet
  11. {
  12. private const string DefaultText = "Ryujinx";
  13. private readonly Switch _device;
  14. private const int StandardBufferSize = 0x7D8;
  15. private const int InteractiveBufferSize = 0x7D4;
  16. private SoftwareKeyboardState _state = SoftwareKeyboardState.Uninitialized;
  17. private AppletSession _normalSession;
  18. private AppletSession _interactiveSession;
  19. private SoftwareKeyboardConfig _keyboardConfig;
  20. private byte[] _transferMemory;
  21. private string _textValue = null;
  22. private bool _okPressed = false;
  23. private Encoding _encoding = Encoding.Unicode;
  24. public event EventHandler AppletStateChanged;
  25. public SoftwareKeyboardApplet(Horizon system)
  26. {
  27. _device = system.Device;
  28. }
  29. public ResultCode Start(AppletSession normalSession,
  30. AppletSession interactiveSession)
  31. {
  32. _normalSession = normalSession;
  33. _interactiveSession = interactiveSession;
  34. _interactiveSession.DataAvailable += OnInteractiveData;
  35. var launchParams = _normalSession.Pop();
  36. var keyboardConfig = _normalSession.Pop();
  37. if (keyboardConfig.Length < Marshal.SizeOf<SoftwareKeyboardConfig>())
  38. {
  39. Logger.Error?.Print(LogClass.ServiceAm, $"SoftwareKeyboardConfig size mismatch. Expected {Marshal.SizeOf<SoftwareKeyboardConfig>():x}. Got {keyboardConfig.Length:x}");
  40. }
  41. else
  42. {
  43. _keyboardConfig = ReadStruct<SoftwareKeyboardConfig>(keyboardConfig);
  44. }
  45. if (!_normalSession.TryPop(out _transferMemory))
  46. {
  47. Logger.Error?.Print(LogClass.ServiceAm, "SwKbd Transfer Memory is null");
  48. }
  49. if (_keyboardConfig.UseUtf8)
  50. {
  51. _encoding = Encoding.UTF8;
  52. }
  53. _state = SoftwareKeyboardState.Ready;
  54. Execute();
  55. return ResultCode.Success;
  56. }
  57. public ResultCode GetResult()
  58. {
  59. return ResultCode.Success;
  60. }
  61. private void Execute()
  62. {
  63. string initialText = null;
  64. // Initial Text is always encoded as a UTF-16 string in the work buffer (passed as transfer memory)
  65. // InitialStringOffset points to the memory offset and InitialStringLength is the number of UTF-16 characters
  66. if (_transferMemory != null && _keyboardConfig.InitialStringLength > 0)
  67. {
  68. initialText = Encoding.Unicode.GetString(_transferMemory, _keyboardConfig.InitialStringOffset, 2 * _keyboardConfig.InitialStringLength);
  69. }
  70. // If the max string length is 0, we set it to a large default
  71. // length.
  72. if (_keyboardConfig.StringLengthMax == 0)
  73. {
  74. _keyboardConfig.StringLengthMax = 100;
  75. }
  76. var args = new SoftwareKeyboardUiArgs
  77. {
  78. HeaderText = _keyboardConfig.HeaderText,
  79. SubtitleText = _keyboardConfig.SubtitleText,
  80. GuideText = _keyboardConfig.GuideText,
  81. SubmitText = (!string.IsNullOrWhiteSpace(_keyboardConfig.SubmitText) ? _keyboardConfig.SubmitText : "OK"),
  82. StringLengthMin = _keyboardConfig.StringLengthMin,
  83. StringLengthMax = _keyboardConfig.StringLengthMax,
  84. InitialText = initialText
  85. };
  86. // Call the configured GUI handler to get user's input
  87. if (_device.UiHandler == null)
  88. {
  89. Logger.Warning?.Print(LogClass.Application, $"GUI Handler is not set. Falling back to default");
  90. _okPressed = true;
  91. }
  92. else
  93. {
  94. _okPressed = _device.UiHandler.DisplayInputDialog(args, out _textValue);
  95. }
  96. _textValue ??= initialText ?? DefaultText;
  97. // If the game requests a string with a minimum length less
  98. // than our default text, repeat our default text until we meet
  99. // the minimum length requirement.
  100. // This should always be done before the text truncation step.
  101. while (_textValue.Length < _keyboardConfig.StringLengthMin)
  102. {
  103. _textValue = String.Join(" ", _textValue, _textValue);
  104. }
  105. // If our default text is longer than the allowed length,
  106. // we truncate it.
  107. if (_textValue.Length > _keyboardConfig.StringLengthMax)
  108. {
  109. _textValue = _textValue.Substring(0, (int)_keyboardConfig.StringLengthMax);
  110. }
  111. // Does the application want to validate the text itself?
  112. if (_keyboardConfig.CheckText)
  113. {
  114. // The application needs to validate the response, so we
  115. // submit it to the interactive output buffer, and poll it
  116. // for validation. Once validated, the application will submit
  117. // back a validation status, which is handled in OnInteractiveDataPushIn.
  118. _state = SoftwareKeyboardState.ValidationPending;
  119. _interactiveSession.Push(BuildResponse(_textValue, true));
  120. }
  121. else
  122. {
  123. // If the application doesn't need to validate the response,
  124. // we push the data to the non-interactive output buffer
  125. // and poll it for completion.
  126. _state = SoftwareKeyboardState.Complete;
  127. _normalSession.Push(BuildResponse(_textValue, false));
  128. AppletStateChanged?.Invoke(this, null);
  129. }
  130. }
  131. private void OnInteractiveData(object sender, EventArgs e)
  132. {
  133. // Obtain the validation status response,
  134. var data = _interactiveSession.Pop();
  135. if (_state == SoftwareKeyboardState.ValidationPending)
  136. {
  137. // TODO(jduncantor):
  138. // If application rejects our "attempt", submit another attempt,
  139. // and put the applet back in PendingValidation state.
  140. // For now we assume success, so we push the final result
  141. // to the standard output buffer and carry on our merry way.
  142. _normalSession.Push(BuildResponse(_textValue, false));
  143. AppletStateChanged?.Invoke(this, null);
  144. _state = SoftwareKeyboardState.Complete;
  145. }
  146. else if(_state == SoftwareKeyboardState.Complete)
  147. {
  148. // If we have already completed, we push the result text
  149. // back on the output buffer and poll the application.
  150. _normalSession.Push(BuildResponse(_textValue, false));
  151. AppletStateChanged?.Invoke(this, null);
  152. }
  153. else
  154. {
  155. // We shouldn't be able to get here through standard swkbd execution.
  156. throw new InvalidOperationException("Software Keyboard is in an invalid state.");
  157. }
  158. }
  159. private byte[] BuildResponse(string text, bool interactive)
  160. {
  161. int bufferSize = interactive ? InteractiveBufferSize : StandardBufferSize;
  162. using (MemoryStream stream = new MemoryStream(new byte[bufferSize]))
  163. using (BinaryWriter writer = new BinaryWriter(stream))
  164. {
  165. byte[] output = _encoding.GetBytes(text);
  166. if (!interactive)
  167. {
  168. // Result Code
  169. writer.Write(_okPressed ? 0U : 1U);
  170. }
  171. else
  172. {
  173. // In interactive mode, we write the length of the text as a long, rather than
  174. // a result code. This field is inclusive of the 64-bit size.
  175. writer.Write((long)output.Length + 8);
  176. }
  177. writer.Write(output);
  178. return stream.ToArray();
  179. }
  180. }
  181. private static T ReadStruct<T>(byte[] data)
  182. where T : struct
  183. {
  184. GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
  185. try
  186. {
  187. return Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
  188. }
  189. finally
  190. {
  191. handle.Free();
  192. }
  193. }
  194. }
  195. }