SoftwareKeyboardRendererBase.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. using Ryujinx.HLE.Ui;
  2. using Ryujinx.Memory;
  3. using SixLabors.ImageSharp;
  4. using SixLabors.ImageSharp.Processing;
  5. using SixLabors.ImageSharp.Drawing.Processing;
  6. using SixLabors.Fonts;
  7. using System;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Numerics;
  11. using System.Reflection;
  12. using System.Runtime.InteropServices;
  13. using SixLabors.ImageSharp.PixelFormats;
  14. namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
  15. {
  16. /// <summary>
  17. /// Base class that generates the graphics for the software keyboard applet during inline mode.
  18. /// </summary>
  19. internal class SoftwareKeyboardRendererBase
  20. {
  21. public const int TextBoxBlinkThreshold = 8;
  22. const string MessageText = "Please use the keyboard to input text";
  23. const string AcceptText = "Accept";
  24. const string CancelText = "Cancel";
  25. const string ControllerToggleText = "Toggle input";
  26. private readonly object _bufferLock = new object();
  27. private RenderingSurfaceInfo _surfaceInfo = null;
  28. private Image<Argb32> _surface = null;
  29. private byte[] _bufferData = null;
  30. private Image _ryujinxLogo = null;
  31. private Image _padAcceptIcon = null;
  32. private Image _padCancelIcon = null;
  33. private Image _keyModeIcon = null;
  34. private float _textBoxOutlineWidth;
  35. private float _padPressedPenWidth;
  36. private Color _textNormalColor;
  37. private Color _textSelectedColor;
  38. private Color _textOverCursorColor;
  39. private IBrush _panelBrush;
  40. private IBrush _disabledBrush;
  41. private IBrush _cursorBrush;
  42. private IBrush _selectionBoxBrush;
  43. private Pen _textBoxOutlinePen;
  44. private Pen _cursorPen;
  45. private Pen _selectionBoxPen;
  46. private Pen _padPressedPen;
  47. private int _inputTextFontSize;
  48. private Font _messageFont;
  49. private Font _inputTextFont;
  50. private Font _labelsTextFont;
  51. private RectangleF _panelRectangle;
  52. private Point _logoPosition;
  53. private float _messagePositionY;
  54. public SoftwareKeyboardRendererBase(IHostUiTheme uiTheme)
  55. {
  56. string ryujinxLogoPath = "Ryujinx.Ui.Resources.Logo_Ryujinx.png";
  57. int ryujinxLogoSize = 32;
  58. _ryujinxLogo = LoadResource(Assembly.GetEntryAssembly(), ryujinxLogoPath, ryujinxLogoSize, ryujinxLogoSize);
  59. string padAcceptIconPath = "Ryujinx.HLE.HOS.Applets.SoftwareKeyboard.Resources.Icon_BtnA.png";
  60. string padCancelIconPath = "Ryujinx.HLE.HOS.Applets.SoftwareKeyboard.Resources.Icon_BtnB.png";
  61. string keyModeIconPath = "Ryujinx.HLE.HOS.Applets.SoftwareKeyboard.Resources.Icon_KeyF6.png";
  62. _padAcceptIcon = LoadResource(Assembly.GetExecutingAssembly(), padAcceptIconPath , 0, 0);
  63. _padCancelIcon = LoadResource(Assembly.GetExecutingAssembly(), padCancelIconPath , 0, 0);
  64. _keyModeIcon = LoadResource(Assembly.GetExecutingAssembly(), keyModeIconPath , 0, 0);
  65. Color panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255);
  66. Color panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150);
  67. Color borderColor = ToColor(uiTheme.DefaultBorderColor);
  68. Color selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor);
  69. _textNormalColor = ToColor(uiTheme.DefaultForegroundColor);
  70. _textSelectedColor = ToColor(uiTheme.SelectionForegroundColor);
  71. _textOverCursorColor = ToColor(uiTheme.DefaultForegroundColor, null, true);
  72. float cursorWidth = 2;
  73. _textBoxOutlineWidth = 2;
  74. _padPressedPenWidth = 2;
  75. _panelBrush = new SolidBrush(panelColor);
  76. _disabledBrush = new SolidBrush(panelTransparentColor);
  77. _cursorBrush = new SolidBrush(_textNormalColor);
  78. _selectionBoxBrush = new SolidBrush(selectionBackgroundColor);
  79. _textBoxOutlinePen = new Pen(borderColor, _textBoxOutlineWidth);
  80. _cursorPen = new Pen(_textNormalColor, cursorWidth);
  81. _selectionBoxPen = new Pen(selectionBackgroundColor, cursorWidth);
  82. _padPressedPen = new Pen(borderColor, _padPressedPenWidth);
  83. _inputTextFontSize = 20;
  84. CreateFonts(uiTheme.FontFamily);
  85. }
  86. private void CreateFonts(string uiThemeFontFamily)
  87. {
  88. // Try a list of fonts in case any of them is not available in the system.
  89. string[] availableFonts = new string[]
  90. {
  91. uiThemeFontFamily,
  92. "Liberation Sans",
  93. "FreeSans",
  94. "DejaVu Sans"
  95. };
  96. foreach (string fontFamily in availableFonts)
  97. {
  98. try
  99. {
  100. _messageFont = SystemFonts.CreateFont(fontFamily, 26, FontStyle.Regular);
  101. _inputTextFont = SystemFonts.CreateFont(fontFamily, _inputTextFontSize, FontStyle.Regular);
  102. _labelsTextFont = SystemFonts.CreateFont(fontFamily, 24, FontStyle.Regular);
  103. return;
  104. }
  105. catch
  106. {
  107. }
  108. }
  109. throw new Exception($"None of these fonts were found in the system: {String.Join(", ", availableFonts)}!");
  110. }
  111. private Color ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false)
  112. {
  113. var a = (byte)(color.A * 255);
  114. var r = (byte)(color.R * 255);
  115. var g = (byte)(color.G * 255);
  116. var b = (byte)(color.B * 255);
  117. if (flipRgb)
  118. {
  119. r = (byte)(255 - r);
  120. g = (byte)(255 - g);
  121. b = (byte)(255 - b);
  122. }
  123. return Color.FromRgba(r, g, b, overrideAlpha.GetValueOrDefault(a));
  124. }
  125. private Image LoadResource(Assembly assembly, string resourcePath, int newWidth, int newHeight)
  126. {
  127. Stream resourceStream = assembly.GetManifestResourceStream(resourcePath);
  128. Debug.Assert(resourceStream != null);
  129. var image = Image.Load(resourceStream);
  130. if (newHeight != 0 && newWidth != 0)
  131. {
  132. image.Mutate(x => x.Resize(newWidth, newHeight, KnownResamplers.Lanczos3));
  133. }
  134. return image;
  135. }
  136. private void SetGraphicsOptions(IImageProcessingContext context)
  137. {
  138. context.GetGraphicsOptions().Antialias = true;
  139. context.GetShapeGraphicsOptions().GraphicsOptions.Antialias = true;
  140. }
  141. private void DrawImmutableElements()
  142. {
  143. if (_surface == null)
  144. {
  145. return;
  146. }
  147. _surface.Mutate(context =>
  148. {
  149. SetGraphicsOptions(context);
  150. context.Clear(Color.Transparent);
  151. context.Fill(_panelBrush, _panelRectangle);
  152. context.DrawImage(_ryujinxLogo, _logoPosition, 1);
  153. float halfWidth = _panelRectangle.Width / 2;
  154. float buttonsY = _panelRectangle.Y + 185;
  155. PointF disableButtonPosition = new PointF(halfWidth + 180, buttonsY);
  156. DrawControllerToggle(context, disableButtonPosition);
  157. });
  158. }
  159. public void DrawMutableElements(SoftwareKeyboardUiState state)
  160. {
  161. if (_surface == null)
  162. {
  163. return;
  164. }
  165. _surface.Mutate(context =>
  166. {
  167. var messageRectangle = MeasureString(MessageText, _messageFont);
  168. float messagePositionX = (_panelRectangle.Width - messageRectangle.Width) / 2 - messageRectangle.X;
  169. float messagePositionY = _messagePositionY - messageRectangle.Y;
  170. var messagePosition = new PointF(messagePositionX, messagePositionY);
  171. var messageBoundRectangle = new RectangleF(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height);
  172. SetGraphicsOptions(context);
  173. context.Fill(_panelBrush, messageBoundRectangle);
  174. context.DrawText(MessageText, _messageFont, _textNormalColor, messagePosition);
  175. if (!state.TypingEnabled)
  176. {
  177. // Just draw a semi-transparent rectangle on top to fade the component with the background.
  178. // TODO (caian): This will not work if one decides to add make background semi-transparent as well.
  179. context.Fill(_disabledBrush, messageBoundRectangle);
  180. }
  181. DrawTextBox(context, state);
  182. float halfWidth = _panelRectangle.Width / 2;
  183. float buttonsY = _panelRectangle.Y + 185;
  184. PointF acceptButtonPosition = new PointF(halfWidth - 180, buttonsY);
  185. PointF cancelButtonPosition = new PointF(halfWidth , buttonsY);
  186. PointF disableButtonPosition = new PointF(halfWidth + 180, buttonsY);
  187. DrawPadButton(context, acceptButtonPosition, _padAcceptIcon, AcceptText, state.AcceptPressed, state.ControllerEnabled);
  188. DrawPadButton(context, cancelButtonPosition, _padCancelIcon, CancelText, state.CancelPressed, state.ControllerEnabled);
  189. });
  190. }
  191. public void CreateSurface(RenderingSurfaceInfo surfaceInfo)
  192. {
  193. if (_surfaceInfo != null)
  194. {
  195. return;
  196. }
  197. _surfaceInfo = surfaceInfo;
  198. Debug.Assert(_surfaceInfo.ColorFormat == Services.SurfaceFlinger.ColorFormat.A8B8G8R8);
  199. // Use the whole area of the image to draw, even the alignment, otherwise it may shear the final
  200. // image if the pitch is different.
  201. uint totalWidth = _surfaceInfo.Pitch / 4;
  202. uint totalHeight = _surfaceInfo.Size / _surfaceInfo.Pitch;
  203. Debug.Assert(_surfaceInfo.Width <= totalWidth);
  204. Debug.Assert(_surfaceInfo.Height <= totalHeight);
  205. Debug.Assert(_surfaceInfo.Pitch * _surfaceInfo.Height <= _surfaceInfo.Size);
  206. _surface = new Image<Argb32>((int)totalWidth, (int)totalHeight);
  207. ComputeConstants();
  208. DrawImmutableElements();
  209. }
  210. private void ComputeConstants()
  211. {
  212. int totalWidth = (int)_surfaceInfo.Width;
  213. int totalHeight = (int)_surfaceInfo.Height;
  214. int panelHeight = 240;
  215. int panelPositionY = totalHeight - panelHeight;
  216. _panelRectangle = new RectangleF(0, panelPositionY, totalWidth, panelHeight);
  217. _messagePositionY = panelPositionY + 60;
  218. int logoPositionX = (totalWidth - _ryujinxLogo.Width) / 2;
  219. int logoPositionY = panelPositionY + 18;
  220. _logoPosition = new Point(logoPositionX, logoPositionY);
  221. }
  222. private RectangleF MeasureString(string text, Font font)
  223. {
  224. RendererOptions options = new RendererOptions(font);
  225. FontRectangle rectangle = TextMeasurer.Measure(text == "" ? " " : text, options);
  226. if (text == "")
  227. {
  228. return new RectangleF(0, rectangle.Y, 0, rectangle.Height);
  229. }
  230. else
  231. {
  232. return new RectangleF(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
  233. }
  234. }
  235. private void DrawTextBox(IImageProcessingContext context, SoftwareKeyboardUiState state)
  236. {
  237. var inputTextRectangle = MeasureString(state.InputText, _inputTextFont);
  238. float boxWidth = (int)(Math.Max(300, inputTextRectangle.Width + inputTextRectangle.X + 8));
  239. float boxHeight = 32;
  240. float boxY = _panelRectangle.Y + 110;
  241. float boxX = (int)((_panelRectangle.Width - boxWidth) / 2);
  242. RectangleF boxRectangle = new RectangleF(boxX, boxY, boxWidth, boxHeight);
  243. RectangleF boundRectangle = new RectangleF(_panelRectangle.X, boxY - _textBoxOutlineWidth,
  244. _panelRectangle.Width, boxHeight + 2 * _textBoxOutlineWidth);
  245. context.Fill(_panelBrush, boundRectangle);
  246. context.Draw(_textBoxOutlinePen, boxRectangle);
  247. float inputTextX = (_panelRectangle.Width - inputTextRectangle.Width) / 2 - inputTextRectangle.X;
  248. float inputTextY = boxY + 5;
  249. var inputTextPosition = new PointF(inputTextX, inputTextY);
  250. context.DrawText(state.InputText, _inputTextFont, _textNormalColor, inputTextPosition);
  251. // Draw the cursor on top of the text and redraw the text with a different color if necessary.
  252. Color cursorTextColor;
  253. IBrush cursorBrush;
  254. Pen cursorPen;
  255. float cursorPositionYTop = inputTextY + 1;
  256. float cursorPositionYBottom = cursorPositionYTop + _inputTextFontSize + 1;
  257. float cursorPositionXLeft;
  258. float cursorPositionXRight;
  259. bool cursorVisible = false;
  260. if (state.CursorBegin != state.CursorEnd)
  261. {
  262. Debug.Assert(state.InputText.Length > 0);
  263. cursorTextColor = _textSelectedColor;
  264. cursorBrush = _selectionBoxBrush;
  265. cursorPen = _selectionBoxPen;
  266. string textUntilBegin = state.InputText.Substring(0, state.CursorBegin);
  267. string textUntilEnd = state.InputText.Substring(0, state.CursorEnd);
  268. var selectionBeginRectangle = MeasureString(textUntilBegin, _inputTextFont);
  269. var selectionEndRectangle = MeasureString(textUntilEnd , _inputTextFont);
  270. cursorVisible = true;
  271. cursorPositionXLeft = inputTextX + selectionBeginRectangle.Width + selectionBeginRectangle.X;
  272. cursorPositionXRight = inputTextX + selectionEndRectangle.Width + selectionEndRectangle.X;
  273. }
  274. else
  275. {
  276. cursorTextColor = _textOverCursorColor;
  277. cursorBrush = _cursorBrush;
  278. cursorPen = _cursorPen;
  279. if (state.TextBoxBlinkCounter < TextBoxBlinkThreshold)
  280. {
  281. // Show the blinking cursor.
  282. int cursorBegin = Math.Min(state.InputText.Length, state.CursorBegin);
  283. string textUntilCursor = state.InputText.Substring(0, cursorBegin);
  284. var cursorTextRectangle = MeasureString(textUntilCursor, _inputTextFont);
  285. cursorVisible = true;
  286. cursorPositionXLeft = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.X;
  287. if (state.OverwriteMode)
  288. {
  289. // The blinking cursor is in overwrite mode so it takes the size of a character.
  290. if (state.CursorBegin < state.InputText.Length)
  291. {
  292. textUntilCursor = state.InputText.Substring(0, cursorBegin + 1);
  293. cursorTextRectangle = MeasureString(textUntilCursor, _inputTextFont);
  294. cursorPositionXRight = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.X;
  295. }
  296. else
  297. {
  298. cursorPositionXRight = cursorPositionXLeft + _inputTextFontSize / 2;
  299. }
  300. }
  301. else
  302. {
  303. // The blinking cursor is in insert mode so it is only a line.
  304. cursorPositionXRight = cursorPositionXLeft;
  305. }
  306. }
  307. else
  308. {
  309. cursorPositionXLeft = inputTextX;
  310. cursorPositionXRight = inputTextX;
  311. }
  312. }
  313. if (state.TypingEnabled && cursorVisible)
  314. {
  315. float cursorWidth = cursorPositionXRight - cursorPositionXLeft;
  316. float cursorHeight = cursorPositionYBottom - cursorPositionYTop;
  317. if (cursorWidth == 0)
  318. {
  319. PointF[] points = new PointF[]
  320. {
  321. new PointF(cursorPositionXLeft, cursorPositionYTop),
  322. new PointF(cursorPositionXLeft, cursorPositionYBottom),
  323. };
  324. context.DrawLines(cursorPen, points);
  325. }
  326. else
  327. {
  328. var cursorRectangle = new RectangleF(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight);
  329. context.Draw(cursorPen , cursorRectangle);
  330. context.Fill(cursorBrush, cursorRectangle);
  331. Image<Argb32> textOverCursor = new Image<Argb32>((int)cursorRectangle.Width, (int)cursorRectangle.Height);
  332. textOverCursor.Mutate(context =>
  333. {
  334. var textRelativePosition = new PointF(inputTextPosition.X - cursorRectangle.X, inputTextPosition.Y - cursorRectangle.Y);
  335. context.DrawText(state.InputText, _inputTextFont, cursorTextColor, textRelativePosition);
  336. });
  337. var cursorPosition = new Point((int)cursorRectangle.X, (int)cursorRectangle.Y);
  338. context.DrawImage(textOverCursor, cursorPosition, 1);
  339. }
  340. }
  341. else if (!state.TypingEnabled)
  342. {
  343. // Just draw a semi-transparent rectangle on top to fade the component with the background.
  344. // TODO (caian): This will not work if one decides to add make background semi-transparent as well.
  345. context.Fill(_disabledBrush, boundRectangle);
  346. }
  347. }
  348. private void DrawPadButton(IImageProcessingContext context, PointF point, Image icon, string label, bool pressed, bool enabled)
  349. {
  350. // Use relative positions so we can center the the entire drawing later.
  351. float iconX = 0;
  352. float iconY = 0;
  353. float iconWidth = icon.Width;
  354. float iconHeight = icon.Height;
  355. var labelRectangle = MeasureString(label, _labelsTextFont);
  356. float labelPositionX = iconWidth + 8 - labelRectangle.X;
  357. float labelPositionY = 3;
  358. float fullWidth = labelPositionX + labelRectangle.Width + labelRectangle.X;
  359. float fullHeight = iconHeight;
  360. // Convert all relative positions into absolute.
  361. float originX = (int)(point.X - fullWidth / 2);
  362. float originY = (int)(point.Y - fullHeight / 2);
  363. iconX += originX;
  364. iconY += originY;
  365. var iconPosition = new Point((int)iconX, (int)iconY);
  366. var labelPosition = new PointF(labelPositionX + originX, labelPositionY + originY);
  367. var selectedRectangle = new RectangleF(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth,
  368. fullWidth + 4 * _padPressedPenWidth, fullHeight + 4 * _padPressedPenWidth);
  369. var boundRectangle = new RectangleF(originX, originY, fullWidth, fullHeight);
  370. boundRectangle.Inflate(4 * _padPressedPenWidth, 4 * _padPressedPenWidth);
  371. context.Fill(_panelBrush, boundRectangle);
  372. context.DrawImage(icon, iconPosition, 1);
  373. context.DrawText(label, _labelsTextFont, _textNormalColor, labelPosition);
  374. if (enabled)
  375. {
  376. if (pressed)
  377. {
  378. context.Draw(_padPressedPen, selectedRectangle);
  379. }
  380. }
  381. else
  382. {
  383. // Just draw a semi-transparent rectangle on top to fade the component with the background.
  384. // TODO (caian): This will not work if one decides to add make background semi-transparent as well.
  385. context.Fill(_disabledBrush, boundRectangle);
  386. }
  387. }
  388. private void DrawControllerToggle(IImageProcessingContext context, PointF point)
  389. {
  390. var labelRectangle = MeasureString(ControllerToggleText, _labelsTextFont);
  391. // Use relative positions so we can center the the entire drawing later.
  392. float keyWidth = _keyModeIcon.Width;
  393. float keyHeight = _keyModeIcon.Height;
  394. float labelPositionX = keyWidth + 8 - labelRectangle.X;
  395. float labelPositionY = -labelRectangle.Y - 1;
  396. float keyX = 0;
  397. float keyY = (int)((labelPositionY + labelRectangle.Height - keyHeight) / 2);
  398. float fullWidth = labelPositionX + labelRectangle.Width;
  399. float fullHeight = Math.Max(labelPositionY + labelRectangle.Height, keyHeight);
  400. // Convert all relative positions into absolute.
  401. float originX = (int)(point.X - fullWidth / 2);
  402. float originY = (int)(point.Y - fullHeight / 2);
  403. keyX += originX;
  404. keyY += originY;
  405. var labelPosition = new PointF(labelPositionX + originX, labelPositionY + originY);
  406. var overlayPosition = new Point((int)keyX, (int)keyY);
  407. context.DrawImage(_keyModeIcon, overlayPosition, 1);
  408. context.DrawText(ControllerToggleText, _labelsTextFont, _textNormalColor, labelPosition);
  409. }
  410. public void CopyImageToBuffer()
  411. {
  412. lock (_bufferLock)
  413. {
  414. if (_surface == null)
  415. {
  416. return;
  417. }
  418. // Convert the pixel format used in the image to the one used in the Switch surface.
  419. if (!_surface.TryGetSinglePixelSpan(out Span<Argb32> pixels))
  420. {
  421. return;
  422. }
  423. _bufferData = MemoryMarshal.AsBytes(pixels).ToArray();
  424. Span<uint> dataConvert = MemoryMarshal.Cast<byte, uint>(_bufferData);
  425. Debug.Assert(_bufferData.Length == _surfaceInfo.Size);
  426. for (int i = 0; i < dataConvert.Length; i++)
  427. {
  428. dataConvert[i] = BitOperations.RotateRight(dataConvert[i], 8);
  429. }
  430. }
  431. }
  432. public bool WriteBufferToMemory(IVirtualMemoryManager destination, ulong position)
  433. {
  434. lock (_bufferLock)
  435. {
  436. if (_bufferData == null)
  437. {
  438. return false;
  439. }
  440. try
  441. {
  442. destination.Write(position, _bufferData);
  443. }
  444. catch
  445. {
  446. return false;
  447. }
  448. return true;
  449. }
  450. }
  451. }
  452. }