Ruler.cs 2.2 KB

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