InputDialog.cs 2.4 KB

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