SwkbdAppletDialog.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Gtk;
  2. using System;
  3. namespace Ryujinx.Ui.Applet
  4. {
  5. public class SwkbdAppletDialog : MessageDialog
  6. {
  7. private int _inputMin;
  8. private int _inputMax;
  9. private Predicate<int> _checkLength;
  10. private readonly Label _validationInfo;
  11. public Entry InputEntry { get; }
  12. public Button OkButton { get; }
  13. public Button CancelButton { get; }
  14. public SwkbdAppletDialog(Window parent) : base(parent, DialogFlags.Modal | DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.None, null)
  15. {
  16. SetDefaultSize(300, 0);
  17. _validationInfo = new Label()
  18. {
  19. Visible = false
  20. };
  21. InputEntry = new Entry()
  22. {
  23. Visible = true
  24. };
  25. InputEntry.Activated += OnInputActivated;
  26. InputEntry.Changed += OnInputChanged;
  27. OkButton = (Button)AddButton("OK", ResponseType.Ok);
  28. CancelButton = (Button)AddButton("Cancel", ResponseType.Cancel);
  29. ((Box)MessageArea).PackEnd(_validationInfo, true, true, 0);
  30. ((Box)MessageArea).PackEnd(InputEntry, true, true, 4);
  31. SetInputLengthValidation(0, int.MaxValue); // Disable by default.
  32. }
  33. public void SetInputLengthValidation(int min, int max)
  34. {
  35. _inputMin = Math.Min(min, max);
  36. _inputMax = Math.Max(min, max);
  37. _validationInfo.Visible = false;
  38. if (_inputMin <= 0 && _inputMax == int.MaxValue) // Disable.
  39. {
  40. _validationInfo.Visible = false;
  41. _checkLength = (length) => true;
  42. }
  43. else if (_inputMin > 0 && _inputMax == int.MaxValue)
  44. {
  45. _validationInfo.Visible = true;
  46. _validationInfo.Markup = $"<i>Must be at least {_inputMin} characters long</i>";
  47. _checkLength = (length) => _inputMin <= length;
  48. }
  49. else
  50. {
  51. _validationInfo.Visible = true;
  52. _validationInfo.Markup = $"<i>Must be {_inputMin}-{_inputMax} characters long</i>";
  53. _checkLength = (length) => _inputMin <= length && length <= _inputMax;
  54. }
  55. OnInputChanged(this, EventArgs.Empty);
  56. }
  57. private void OnInputActivated(object sender, EventArgs e)
  58. {
  59. if (OkButton.IsSensitive)
  60. {
  61. Respond(ResponseType.Ok);
  62. }
  63. }
  64. private void OnInputChanged(object sender, EventArgs e)
  65. {
  66. OkButton.Sensitive = _checkLength(InputEntry.Text.Length);
  67. }
  68. }
  69. }