Ruler.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using NStack;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Text;
  6. using System.Text.Json.Serialization;
  7. using Terminal.Gui.Configuration;
  8. using Terminal.Gui.Graphs;
  9. namespace Terminal.Gui {
  10. /// <summary>
  11. /// Draws a ruler on the screen.
  12. /// </summary>
  13. /// <remarks>
  14. /// <para>
  15. /// </para>
  16. /// </remarks>
  17. public class Ruler {
  18. /// <summary>
  19. /// Gets or sets whether the ruler is drawn horizontally or vertically. The default is horizontally.
  20. /// </summary>
  21. public Orientation Orientation { get; set; }
  22. /// <summary>
  23. /// Gets or sets the lenght of the ruler. The default is 0.
  24. /// </summary>
  25. public int Length { get; set; }
  26. /// <summary>
  27. /// Gets or sets the foreground and backgrond color to use.
  28. /// </summary>
  29. public Attribute Attribute { get; set; }
  30. string _hTemplate { get; set; } = "|123456789";
  31. string _vTemplate { get; set; } = "-123456789";
  32. /// <summary>
  33. /// Draws the <see cref="Ruler"/>.
  34. /// </summary>
  35. /// <param name="location">The location to start drawing the ruler, in screen-relative coordinates.</param>
  36. /// <param name="start">The start value of the ruler.</param>
  37. public void Draw (Point location, int start = 0)
  38. {
  39. if (start < 0) {
  40. throw new ArgumentException ("start must be greater than or equal to 0");
  41. }
  42. if (Length < 1) {
  43. return;
  44. }
  45. if (Orientation == Orientation.Horizontal) {
  46. var hrule = _hTemplate.Repeat ((int)Math.Ceiling ((double)Length + 2 / (double)_hTemplate.Length)) [start..(Length + start)];
  47. // Top
  48. Application.Driver.Move (location.X, location.Y);
  49. Application.Driver.AddStr (hrule);
  50. } else {
  51. var vrule = _vTemplate.Repeat ((int)Math.Ceiling ((double)(Length + 2) / (double)_vTemplate.Length)) [start..(Length + start)];
  52. for (var r = location.Y; r < location.Y + Length; r++) {
  53. Application.Driver.Move (location.X, r);
  54. Application.Driver.AddRune (vrule [r - location.Y]);
  55. }
  56. }
  57. }
  58. }
  59. internal static class StringExtensions {
  60. public static string Repeat (this string instr, int n)
  61. {
  62. if (n <= 0) {
  63. return null;
  64. }
  65. if (string.IsNullOrEmpty (instr) || n == 1) {
  66. return instr;
  67. }
  68. return new StringBuilder (instr.Length * n)
  69. .Insert (0, instr, n)
  70. .ToString ();
  71. }
  72. }
  73. }