SoftwareKeyboardApplet.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.HLE.HOS.Applets.SoftwareKeyboard;
  4. using Ryujinx.HLE.HOS.Services.Am.AppletAE;
  5. using System;
  6. using System.IO;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace Ryujinx.HLE.HOS.Applets
  12. {
  13. internal class SoftwareKeyboardApplet : IApplet
  14. {
  15. private const string DefaultText = "Ryujinx";
  16. private const long DebounceTimeMillis = 200;
  17. private const int ResetDelayMillis = 500;
  18. private readonly Switch _device;
  19. private const int StandardBufferSize = 0x7D8;
  20. private const int InteractiveBufferSize = 0x7D4;
  21. private const int MaxUserWords = 0x1388;
  22. private SoftwareKeyboardState _foregroundState = SoftwareKeyboardState.Uninitialized;
  23. private volatile InlineKeyboardState _backgroundState = InlineKeyboardState.Uninitialized;
  24. private bool _isBackground = false;
  25. private bool _alreadyShown = false;
  26. private volatile bool _useChangedStringV2 = false;
  27. private AppletSession _normalSession;
  28. private AppletSession _interactiveSession;
  29. // Configuration for foreground mode.
  30. private SoftwareKeyboardConfig _keyboardForegroundConfig;
  31. // Configuration for background (inline) mode.
  32. private SoftwareKeyboardInitialize _keyboardBackgroundInitialize;
  33. private SoftwareKeyboardCalc _keyboardBackgroundCalc;
  34. private SoftwareKeyboardCustomizeDic _keyboardBackgroundDic;
  35. private SoftwareKeyboardDictSet _keyboardBackgroundDictSet;
  36. private SoftwareKeyboardUserWord[] _keyboardBackgroundUserWords;
  37. private byte[] _transferMemory;
  38. private string _textValue = "";
  39. private bool _okPressed = false;
  40. private Encoding _encoding = Encoding.Unicode;
  41. private long _lastTextSetMillis = 0;
  42. public event EventHandler AppletStateChanged;
  43. public SoftwareKeyboardApplet(Horizon system)
  44. {
  45. _device = system.Device;
  46. }
  47. public ResultCode Start(AppletSession normalSession,
  48. AppletSession interactiveSession)
  49. {
  50. _normalSession = normalSession;
  51. _interactiveSession = interactiveSession;
  52. _interactiveSession.DataAvailable += OnInteractiveData;
  53. _alreadyShown = false;
  54. _useChangedStringV2 = false;
  55. var launchParams = _normalSession.Pop();
  56. var keyboardConfig = _normalSession.Pop();
  57. if (keyboardConfig.Length == Marshal.SizeOf<SoftwareKeyboardInitialize>())
  58. {
  59. // Initialize the keyboard applet in background mode.
  60. _isBackground = true;
  61. _keyboardBackgroundInitialize = ReadStruct<SoftwareKeyboardInitialize>(keyboardConfig);
  62. _backgroundState = InlineKeyboardState.Uninitialized;
  63. return ResultCode.Success;
  64. }
  65. else
  66. {
  67. // Initialize the keyboard applet in foreground mode.
  68. _isBackground = false;
  69. if (keyboardConfig.Length < Marshal.SizeOf<SoftwareKeyboardConfig>())
  70. {
  71. Logger.Error?.Print(LogClass.ServiceAm, $"SoftwareKeyboardConfig size mismatch. Expected {Marshal.SizeOf<SoftwareKeyboardConfig>():x}. Got {keyboardConfig.Length:x}");
  72. }
  73. else
  74. {
  75. _keyboardForegroundConfig = ReadStruct<SoftwareKeyboardConfig>(keyboardConfig);
  76. }
  77. if (!_normalSession.TryPop(out _transferMemory))
  78. {
  79. Logger.Error?.Print(LogClass.ServiceAm, "SwKbd Transfer Memory is null");
  80. }
  81. if (_keyboardForegroundConfig.UseUtf8)
  82. {
  83. _encoding = Encoding.UTF8;
  84. }
  85. _foregroundState = SoftwareKeyboardState.Ready;
  86. ExecuteForegroundKeyboard();
  87. return ResultCode.Success;
  88. }
  89. }
  90. public ResultCode GetResult()
  91. {
  92. return ResultCode.Success;
  93. }
  94. private InlineKeyboardState GetInlineState()
  95. {
  96. return _backgroundState;
  97. }
  98. private void SetInlineState(InlineKeyboardState state)
  99. {
  100. _backgroundState = state;
  101. }
  102. private void ExecuteForegroundKeyboard()
  103. {
  104. string initialText = null;
  105. // Initial Text is always encoded as a UTF-16 string in the work buffer (passed as transfer memory)
  106. // InitialStringOffset points to the memory offset and InitialStringLength is the number of UTF-16 characters
  107. if (_transferMemory != null && _keyboardForegroundConfig.InitialStringLength > 0)
  108. {
  109. initialText = Encoding.Unicode.GetString(_transferMemory, _keyboardForegroundConfig.InitialStringOffset,
  110. 2 * _keyboardForegroundConfig.InitialStringLength);
  111. }
  112. // If the max string length is 0, we set it to a large default
  113. // length.
  114. if (_keyboardForegroundConfig.StringLengthMax == 0)
  115. {
  116. _keyboardForegroundConfig.StringLengthMax = 100;
  117. }
  118. var args = new SoftwareKeyboardUiArgs
  119. {
  120. HeaderText = _keyboardForegroundConfig.HeaderText,
  121. SubtitleText = _keyboardForegroundConfig.SubtitleText,
  122. GuideText = _keyboardForegroundConfig.GuideText,
  123. SubmitText = (!string.IsNullOrWhiteSpace(_keyboardForegroundConfig.SubmitText) ?
  124. _keyboardForegroundConfig.SubmitText : "OK"),
  125. StringLengthMin = _keyboardForegroundConfig.StringLengthMin,
  126. StringLengthMax = _keyboardForegroundConfig.StringLengthMax,
  127. InitialText = initialText
  128. };
  129. // Call the configured GUI handler to get user's input
  130. if (_device.UiHandler == null)
  131. {
  132. Logger.Warning?.Print(LogClass.Application, "GUI Handler is not set. Falling back to default");
  133. _okPressed = true;
  134. }
  135. else
  136. {
  137. _okPressed = _device.UiHandler.DisplayInputDialog(args, out _textValue);
  138. }
  139. _textValue ??= initialText ?? DefaultText;
  140. // If the game requests a string with a minimum length less
  141. // than our default text, repeat our default text until we meet
  142. // the minimum length requirement.
  143. // This should always be done before the text truncation step.
  144. while (_textValue.Length < _keyboardForegroundConfig.StringLengthMin)
  145. {
  146. _textValue = String.Join(" ", _textValue, _textValue);
  147. }
  148. // If our default text is longer than the allowed length,
  149. // we truncate it.
  150. if (_textValue.Length > _keyboardForegroundConfig.StringLengthMax)
  151. {
  152. _textValue = _textValue.Substring(0, (int)_keyboardForegroundConfig.StringLengthMax);
  153. }
  154. // Does the application want to validate the text itself?
  155. if (_keyboardForegroundConfig.CheckText)
  156. {
  157. // The application needs to validate the response, so we
  158. // submit it to the interactive output buffer, and poll it
  159. // for validation. Once validated, the application will submit
  160. // back a validation status, which is handled in OnInteractiveDataPushIn.
  161. _foregroundState = SoftwareKeyboardState.ValidationPending;
  162. _interactiveSession.Push(BuildResponse(_textValue, true));
  163. }
  164. else
  165. {
  166. // If the application doesn't need to validate the response,
  167. // we push the data to the non-interactive output buffer
  168. // and poll it for completion.
  169. _foregroundState = SoftwareKeyboardState.Complete;
  170. _normalSession.Push(BuildResponse(_textValue, false));
  171. AppletStateChanged?.Invoke(this, null);
  172. }
  173. }
  174. private void OnInteractiveData(object sender, EventArgs e)
  175. {
  176. // Obtain the validation status response.
  177. var data = _interactiveSession.Pop();
  178. if (_isBackground)
  179. {
  180. OnBackgroundInteractiveData(data);
  181. }
  182. else
  183. {
  184. OnForegroundInteractiveData(data);
  185. }
  186. }
  187. private void OnForegroundInteractiveData(byte[] data)
  188. {
  189. if (_foregroundState == SoftwareKeyboardState.ValidationPending)
  190. {
  191. // TODO(jduncantor):
  192. // If application rejects our "attempt", submit another attempt,
  193. // and put the applet back in PendingValidation state.
  194. // For now we assume success, so we push the final result
  195. // to the standard output buffer and carry on our merry way.
  196. _normalSession.Push(BuildResponse(_textValue, false));
  197. AppletStateChanged?.Invoke(this, null);
  198. _foregroundState = SoftwareKeyboardState.Complete;
  199. }
  200. else if(_foregroundState == SoftwareKeyboardState.Complete)
  201. {
  202. // If we have already completed, we push the result text
  203. // back on the output buffer and poll the application.
  204. _normalSession.Push(BuildResponse(_textValue, false));
  205. AppletStateChanged?.Invoke(this, null);
  206. }
  207. else
  208. {
  209. // We shouldn't be able to get here through standard swkbd execution.
  210. throw new InvalidOperationException("Software Keyboard is in an invalid state.");
  211. }
  212. }
  213. private void OnBackgroundInteractiveData(byte[] data)
  214. {
  215. // WARNING: Only invoke applet state changes after an explicit finalization
  216. // request from the game, this is because the inline keyboard is expected to
  217. // keep running in the background sending data by itself.
  218. using (MemoryStream stream = new MemoryStream(data))
  219. using (BinaryReader reader = new BinaryReader(stream))
  220. {
  221. InlineKeyboardRequest request = (InlineKeyboardRequest)reader.ReadUInt32();
  222. InlineKeyboardState state = GetInlineState();
  223. long remaining;
  224. Logger.Debug?.Print(LogClass.ServiceAm, $"Keyboard received command {request} in state {state}");
  225. switch (request)
  226. {
  227. case InlineKeyboardRequest.UseChangedStringV2:
  228. _useChangedStringV2 = true;
  229. break;
  230. case InlineKeyboardRequest.UseMovedCursorV2:
  231. // Not used because we only reply with the final string.
  232. break;
  233. case InlineKeyboardRequest.SetUserWordInfo:
  234. // Read the user word info data.
  235. remaining = stream.Length - stream.Position;
  236. if (remaining < sizeof(int))
  237. {
  238. Logger.Warning?.Print(LogClass.ServiceAm, $"Received invalid Software Keyboard User Word Info of {remaining} bytes");
  239. }
  240. else
  241. {
  242. int wordsCount = reader.ReadInt32();
  243. int wordSize = Marshal.SizeOf<SoftwareKeyboardUserWord>();
  244. remaining = stream.Length - stream.Position;
  245. if (wordsCount > MaxUserWords)
  246. {
  247. Logger.Warning?.Print(LogClass.ServiceAm, $"Received {wordsCount} User Words but the maximum is {MaxUserWords}");
  248. }
  249. else if (wordsCount * wordSize != remaining)
  250. {
  251. Logger.Warning?.Print(LogClass.ServiceAm, $"Received invalid Software Keyboard User Word Info data of {remaining} bytes for {wordsCount} words");
  252. }
  253. else
  254. {
  255. _keyboardBackgroundUserWords = new SoftwareKeyboardUserWord[wordsCount];
  256. for (int word = 0; word < wordsCount; word++)
  257. {
  258. byte[] wordData = reader.ReadBytes(wordSize);
  259. _keyboardBackgroundUserWords[word] = ReadStruct<SoftwareKeyboardUserWord>(wordData);
  260. }
  261. }
  262. }
  263. _interactiveSession.Push(InlineResponses.ReleasedUserWordInfo(state));
  264. break;
  265. case InlineKeyboardRequest.SetCustomizeDic:
  266. // Read the custom dic data.
  267. remaining = stream.Length - stream.Position;
  268. if (remaining != Marshal.SizeOf<SoftwareKeyboardCustomizeDic>())
  269. {
  270. Logger.Warning?.Print(LogClass.ServiceAm, $"Received invalid Software Keyboard Customize Dic of {remaining} bytes");
  271. }
  272. else
  273. {
  274. var keyboardDicData = reader.ReadBytes((int)remaining);
  275. _keyboardBackgroundDic = ReadStruct<SoftwareKeyboardCustomizeDic>(keyboardDicData);
  276. }
  277. _interactiveSession.Push(InlineResponses.UnsetCustomizeDic(state));
  278. break;
  279. case InlineKeyboardRequest.SetCustomizedDictionaries:
  280. // Read the custom dictionaries data.
  281. remaining = stream.Length - stream.Position;
  282. if (remaining != Marshal.SizeOf<SoftwareKeyboardDictSet>())
  283. {
  284. Logger.Warning?.Print(LogClass.ServiceAm, $"Received invalid Software Keyboard DictSet of {remaining} bytes");
  285. }
  286. else
  287. {
  288. var keyboardDictData = reader.ReadBytes((int)remaining);
  289. _keyboardBackgroundDictSet = ReadStruct<SoftwareKeyboardDictSet>(keyboardDictData);
  290. }
  291. _interactiveSession.Push(InlineResponses.UnsetCustomizedDictionaries(state));
  292. break;
  293. case InlineKeyboardRequest.Calc:
  294. // The Calc request tells the Applet to enter the main input handling loop, which will end
  295. // with either a text being submitted or a cancel request from the user.
  296. // NOTE: Some Calc requests happen early in the process and are not meant to be shown. This possibly
  297. // happens because the game has complete control over when the inline keyboard is drawn, but here it
  298. // would cause a dialog to pop in the emulator, which is inconvenient. An algorithm is applied to
  299. // decide whether it is a dummy Calc or not, but regardless of the result, the dummy Calc appears to
  300. // never happen twice, so the keyboard will always show if it has already been shown before.
  301. bool forceShowKeyboard = _alreadyShown;
  302. _alreadyShown = true;
  303. // Read the Calc data.
  304. remaining = stream.Length - stream.Position;
  305. if (remaining != Marshal.SizeOf<SoftwareKeyboardCalc>())
  306. {
  307. Logger.Error?.Print(LogClass.ServiceAm, $"Received invalid Software Keyboard Calc of {remaining} bytes");
  308. }
  309. else
  310. {
  311. var keyboardCalcData = reader.ReadBytes((int)remaining);
  312. _keyboardBackgroundCalc = ReadStruct<SoftwareKeyboardCalc>(keyboardCalcData);
  313. // Check if the application expects UTF8 encoding instead of UTF16.
  314. if (_keyboardBackgroundCalc.UseUtf8)
  315. {
  316. _encoding = Encoding.UTF8;
  317. }
  318. // Force showing the keyboard regardless of the state, an unwanted
  319. // input dialog may show, but it is better than a soft lock.
  320. if (_keyboardBackgroundCalc.Appear.ShouldBeHidden == 0)
  321. {
  322. forceShowKeyboard = true;
  323. }
  324. }
  325. // Send an initialization finished signal.
  326. state = InlineKeyboardState.Ready;
  327. SetInlineState(state);
  328. _interactiveSession.Push(InlineResponses.FinishedInitialize(state));
  329. // Start a task with the GUI handler to get user's input.
  330. new Task(() => { GetInputTextAndSend(forceShowKeyboard, state); }).Start();
  331. break;
  332. case InlineKeyboardRequest.Finalize:
  333. // The calling process wants to close the keyboard applet and will wait for a state change.
  334. _backgroundState = InlineKeyboardState.Uninitialized;
  335. AppletStateChanged?.Invoke(this, null);
  336. break;
  337. default:
  338. // We shouldn't be able to get here through standard swkbd execution.
  339. Logger.Warning?.Print(LogClass.ServiceAm, $"Invalid Software Keyboard request {request} during state {_backgroundState}");
  340. _interactiveSession.Push(InlineResponses.Default(state));
  341. break;
  342. }
  343. }
  344. }
  345. private void GetInputTextAndSend(bool forceShowKeyboard, InlineKeyboardState oldState)
  346. {
  347. bool submit = true;
  348. // Use the text specified by the Calc if it is available, otherwise use the default one.
  349. string inputText = (!string.IsNullOrWhiteSpace(_keyboardBackgroundCalc.InputText) ?
  350. _keyboardBackgroundCalc.InputText : DefaultText);
  351. // Compute the elapsed time for the debouncing algorithm.
  352. long currentMillis = PerformanceCounter.ElapsedMilliseconds;
  353. long inputElapsedMillis = currentMillis - _lastTextSetMillis;
  354. // Reset the input text before submitting the final result, that's because some games do not expect
  355. // consecutive submissions to abruptly shrink and they will crash if it happens. Changing the string
  356. // before the final submission prevents that.
  357. InlineKeyboardState newState = InlineKeyboardState.DataAvailable;
  358. SetInlineState(newState);
  359. ChangedString("", newState);
  360. if (inputElapsedMillis < DebounceTimeMillis)
  361. {
  362. // A repeated Calc request has been received without player interaction, after the input has been
  363. // sent. This behavior happens in some games, so instead of showing another dialog, just apply a
  364. // time-based debouncing algorithm and repeat the last submission, either a value or a cancel.
  365. inputText = _textValue;
  366. submit = _textValue != null;
  367. Logger.Warning?.Print(LogClass.Application, "Debouncing repeated keyboard request");
  368. }
  369. else if (!forceShowKeyboard)
  370. {
  371. // Submit the default text to avoid soft locking if the keyboard was ignored by
  372. // accident. It's better to change the name than being locked out of the game.
  373. inputText = DefaultText;
  374. Logger.Debug?.Print(LogClass.Application, "Received a dummy Calc, keyboard will not be shown");
  375. }
  376. else if (_device.UiHandler == null)
  377. {
  378. Logger.Warning?.Print(LogClass.Application, "GUI Handler is not set. Falling back to default");
  379. }
  380. else
  381. {
  382. // Call the configured GUI handler to get user's input.
  383. var args = new SoftwareKeyboardUiArgs
  384. {
  385. HeaderText = "", // The inline keyboard lacks these texts
  386. SubtitleText = "",
  387. GuideText = "",
  388. SubmitText = (!string.IsNullOrWhiteSpace(_keyboardBackgroundCalc.Appear.OkText) ?
  389. _keyboardBackgroundCalc.Appear.OkText : "OK"),
  390. StringLengthMin = 0,
  391. StringLengthMax = 100,
  392. InitialText = inputText
  393. };
  394. submit = _device.UiHandler.DisplayInputDialog(args, out inputText);
  395. inputText = submit ? inputText : null;
  396. }
  397. // The 'Complete' state indicates the Calc request has been fulfilled by the applet.
  398. newState = InlineKeyboardState.Complete;
  399. if (submit)
  400. {
  401. Logger.Debug?.Print(LogClass.ServiceAm, "Sending keyboard OK");
  402. DecidedEnter(inputText, newState);
  403. }
  404. else
  405. {
  406. Logger.Debug?.Print(LogClass.ServiceAm, "Sending keyboard Cancel");
  407. DecidedCancel(newState);
  408. }
  409. _interactiveSession.Push(InlineResponses.Default(newState));
  410. // The constant calls to PopInteractiveData suggest that the keyboard applet continuously reports
  411. // data back to the application and this can also be time-sensitive. Pushing a state reset right
  412. // after the data has been sent does not work properly and the application will soft-lock. This
  413. // delay gives time for the application to catch up with the data and properly process the state
  414. // reset.
  415. Thread.Sleep(ResetDelayMillis);
  416. // 'Initialized' is the only known state so far that does not soft-lock the keyboard after use.
  417. newState = InlineKeyboardState.Initialized;
  418. Logger.Debug?.Print(LogClass.ServiceAm, $"Resetting state of the keyboard to {newState}");
  419. SetInlineState(newState);
  420. _interactiveSession.Push(InlineResponses.Default(newState));
  421. // Keep the text and the timestamp of the input for the debouncing algorithm.
  422. _textValue = inputText;
  423. _lastTextSetMillis = PerformanceCounter.ElapsedMilliseconds;
  424. }
  425. private void ChangedString(string text, InlineKeyboardState state)
  426. {
  427. if (_encoding == Encoding.UTF8)
  428. {
  429. if (_useChangedStringV2)
  430. {
  431. _interactiveSession.Push(InlineResponses.ChangedStringUtf8V2(text, state));
  432. }
  433. else
  434. {
  435. _interactiveSession.Push(InlineResponses.ChangedStringUtf8(text, state));
  436. }
  437. }
  438. else
  439. {
  440. if (_useChangedStringV2)
  441. {
  442. _interactiveSession.Push(InlineResponses.ChangedStringV2(text, state));
  443. }
  444. else
  445. {
  446. _interactiveSession.Push(InlineResponses.ChangedString(text, state));
  447. }
  448. }
  449. }
  450. private void DecidedEnter(string text, InlineKeyboardState state)
  451. {
  452. if (_encoding == Encoding.UTF8)
  453. {
  454. _interactiveSession.Push(InlineResponses.DecidedEnterUtf8(text, state));
  455. }
  456. else
  457. {
  458. _interactiveSession.Push(InlineResponses.DecidedEnter(text, state));
  459. }
  460. }
  461. private void DecidedCancel(InlineKeyboardState state)
  462. {
  463. _interactiveSession.Push(InlineResponses.DecidedCancel(state));
  464. }
  465. private byte[] BuildResponse(string text, bool interactive)
  466. {
  467. int bufferSize = interactive ? InteractiveBufferSize : StandardBufferSize;
  468. using (MemoryStream stream = new MemoryStream(new byte[bufferSize]))
  469. using (BinaryWriter writer = new BinaryWriter(stream))
  470. {
  471. byte[] output = _encoding.GetBytes(text);
  472. if (!interactive)
  473. {
  474. // Result Code
  475. writer.Write(_okPressed ? 0U : 1U);
  476. }
  477. else
  478. {
  479. // In interactive mode, we write the length of the text as a long, rather than
  480. // a result code. This field is inclusive of the 64-bit size.
  481. writer.Write((long)output.Length + 8);
  482. }
  483. writer.Write(output);
  484. return stream.ToArray();
  485. }
  486. }
  487. private static T ReadStruct<T>(byte[] data)
  488. where T : struct
  489. {
  490. GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
  491. try
  492. {
  493. return Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
  494. }
  495. finally
  496. {
  497. handle.Free();
  498. }
  499. }
  500. }
  501. }