ProgressBar.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. namespace Terminal.Gui {
  3. /// <summary>
  4. /// Progress bar can indicate progress of an activity visually.
  5. /// </summary>
  6. /// <remarks>
  7. /// <para>
  8. /// The progressbar can operate in two modes, percentage mode, or
  9. /// activity mode. The progress bar starts in percentage mode and
  10. /// setting the Fraction property will reflect on the UI the progress
  11. /// made so far. Activity mode is used when the application has no
  12. /// way of knowing how much time is left, and is started when you invoke
  13. /// the Pulse() method. You should call the Pulse method repeatedly as
  14. /// your application makes progress.
  15. /// </para>
  16. /// </remarks>
  17. public class ProgressBar : View {
  18. bool isActivity;
  19. int activityPos, delta;
  20. /// <summary>
  21. /// Initializes a new instance of the <see cref="T:Terminal.Gui.ProgressBar"/> class, starts in percentage mode.
  22. /// </summary>
  23. /// <param name="rect">Rect.</param>
  24. public ProgressBar (Rect rect) : base (rect)
  25. {
  26. CanFocus = false;
  27. fraction = 0;
  28. }
  29. float fraction;
  30. /// <summary>
  31. /// Gets or sets the progress indicator fraction to display, must be a value between 0 and 1.
  32. /// </summary>
  33. /// <value>The fraction representing the progress.</value>
  34. public float Fraction {
  35. get => fraction;
  36. set {
  37. fraction = value;
  38. isActivity = false;
  39. SetNeedsDisplay ();
  40. }
  41. }
  42. /// <summary>
  43. /// Notifies the progress bar that some progress has taken place.
  44. /// </summary>
  45. /// <remarks>
  46. /// If the ProgressBar is is percentage mode, it switches to activity
  47. /// mode. If is in activity mode, the marker is moved.
  48. /// </remarks>
  49. public void Pulse ()
  50. {
  51. if (!isActivity) {
  52. isActivity = true;
  53. activityPos = 0;
  54. delta = 1;
  55. } else {
  56. activityPos += delta;
  57. if (activityPos < 0) {
  58. activityPos = 1;
  59. delta = 1;
  60. } else if (activityPos >= Frame.Width) {
  61. activityPos = Frame.Width - 2;
  62. delta = -1;
  63. }
  64. }
  65. SetNeedsDisplay ();
  66. }
  67. public override void Redraw(Rect region)
  68. {
  69. Driver.SetAttribute (ColorScheme.Normal);
  70. int top = Frame.Width;
  71. if (isActivity) {
  72. Move (0, 0);
  73. for (int i = 0; i < top; i++)
  74. if (i == activityPos)
  75. Driver.AddRune (Driver.Stipple);
  76. else
  77. Driver.AddRune (' ');
  78. } else {
  79. Move (0, 0);
  80. int mid = (int)(fraction * top);
  81. int i;
  82. for (i = 0; i < mid; i++)
  83. Driver.AddRune (Driver.Stipple);
  84. for (; i < top; i++)
  85. Driver.AddRune (' ');
  86. }
  87. }
  88. }
  89. }