SoftwareKeyboardApplet.cs 26 KB

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