GraphView.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using System.Text;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. #nullable enable
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// Control for rendering graphs (bar, scatter etc)
  9. /// </summary>
  10. public class GraphView : View {
  11. /// <summary>
  12. /// Horizontal axis
  13. /// </summary>
  14. /// <value></value>
  15. public HorizontalAxis AxisX { get; set; }
  16. /// <summary>
  17. /// Vertical axis
  18. /// </summary>
  19. /// <value></value>
  20. public VerticalAxis AxisY { get; set; }
  21. /// <summary>
  22. /// Collection of data series that are rendered in the graph
  23. /// </summary>
  24. public List<ISeries> Series { get; } = new List<ISeries> ();
  25. /// <summary>
  26. /// Elements drawn into graph after series have been drawn e.g. Legends etc
  27. /// </summary>
  28. public List<IAnnotation> Annotations { get; } = new List<IAnnotation> ();
  29. /// <summary>
  30. /// Amount of space to leave on left of control. Graph content (<see cref="Series"/>)
  31. /// will not be rendered in margins but axis labels may be
  32. /// </summary>
  33. public uint MarginLeft { get; set; }
  34. /// <summary>
  35. /// Amount of space to leave on bottom of control. Graph content (<see cref="Series"/>)
  36. /// will not be rendered in margins but axis labels may be
  37. /// </summary>
  38. public uint MarginBottom { get; set; }
  39. /// <summary>
  40. /// The graph space position of the bottom left of the control.
  41. /// Changing this scrolls the viewport around in the graph
  42. /// </summary>
  43. /// <value></value>
  44. public PointF ScrollOffset { get; set; } = new PointF (0, 0);
  45. /// <summary>
  46. /// Translates console width/height into graph space. Defaults
  47. /// to 1 row/col of console space being 1 unit of graph space.
  48. /// </summary>
  49. /// <returns></returns>
  50. public PointF CellSize { get; set; } = new PointF (1, 1);
  51. /// <summary>
  52. /// The color of the background of the graph and axis/labels
  53. /// </summary>
  54. public Attribute? GraphColor { get; set; }
  55. /// <summary>
  56. /// Creates a new graph with a 1 to 1 graph space with absolute layout
  57. /// </summary>
  58. public GraphView ()
  59. {
  60. CanFocus = true;
  61. AxisX = new HorizontalAxis ();
  62. AxisY = new VerticalAxis ();
  63. // Things this view knows how to do
  64. AddCommand (Command.ScrollUp, () => { Scroll (0, CellSize.Y); return true; });
  65. AddCommand (Command.ScrollDown, () => { Scroll (0, -CellSize.Y); return true; });
  66. AddCommand (Command.ScrollRight, () => { Scroll (CellSize.X, 0); return true; });
  67. AddCommand (Command.ScrollLeft, () => { Scroll (-CellSize.X, 0); return true; });
  68. AddCommand (Command.PageUp, () => { PageUp (); return true; });
  69. AddCommand (Command.PageDown, () => { PageDown (); return true; });
  70. KeyBindings.Add (KeyCode.CursorRight, Command.ScrollRight);
  71. KeyBindings.Add (KeyCode.CursorLeft, Command.ScrollLeft);
  72. KeyBindings.Add (KeyCode.CursorUp, Command.ScrollUp);
  73. KeyBindings.Add (KeyCode.CursorDown, Command.ScrollDown);
  74. // Not bound by default (preserves backwards compatibility)
  75. //KeyBindings.Add (Key.PageUp, Command.PageUp);
  76. //KeyBindings.Add (Key.PageDown, Command.PageDown);
  77. }
  78. /// <summary>
  79. /// Clears all settings configured on the graph and resets all properties
  80. /// to default values (<see cref="CellSize"/>, <see cref="ScrollOffset"/> etc)
  81. /// </summary>
  82. public void Reset ()
  83. {
  84. ScrollOffset = new PointF (0, 0);
  85. CellSize = new PointF (1, 1);
  86. AxisX.Reset ();
  87. AxisY.Reset ();
  88. Series.Clear ();
  89. Annotations.Clear ();
  90. GraphColor = null;
  91. SetNeedsDisplay ();
  92. }
  93. ///<inheritdoc/>
  94. public override void OnDrawContent (Rect contentArea)
  95. {
  96. if (CellSize.X == 0 || CellSize.Y == 0) {
  97. throw new Exception ($"{nameof (CellSize)} cannot be 0");
  98. }
  99. SetDriverColorToGraphColor ();
  100. Move (0, 0);
  101. // clear all old content
  102. for (int i = 0; i < Bounds.Height; i++) {
  103. Move (0, i);
  104. Driver.AddStr (new string (' ', Bounds.Width));
  105. }
  106. // If there is no data do not display a graph
  107. if (!Series.Any () && !Annotations.Any ()) {
  108. return;
  109. }
  110. // The drawable area of the graph (anything that isn't in the margins)
  111. var graphScreenWidth = Bounds.Width - ((int)MarginLeft);
  112. var graphScreenHeight = Bounds.Height - (int)MarginBottom;
  113. // if the margins take up the full draw bounds don't render
  114. if (graphScreenWidth < 0 || graphScreenHeight < 0) {
  115. return;
  116. }
  117. // Draw 'before' annotations
  118. foreach (var a in Annotations.ToArray ().Where (a => a.BeforeSeries)) {
  119. a.Render (this);
  120. }
  121. SetDriverColorToGraphColor ();
  122. AxisY.DrawAxisLine (this);
  123. AxisX.DrawAxisLine (this);
  124. AxisY.DrawAxisLabels (this);
  125. AxisX.DrawAxisLabels (this);
  126. // Draw a cross where the two axis cross
  127. var axisIntersection = new Point (AxisY.GetAxisXPosition (this), AxisX.GetAxisYPosition (this));
  128. if (AxisX.Visible && AxisY.Visible) {
  129. Move (axisIntersection.X, axisIntersection.Y);
  130. AddRune (axisIntersection.X, axisIntersection.Y, (Rune)'\u253C');
  131. }
  132. SetDriverColorToGraphColor ();
  133. Rect drawBounds = new Rect ((int)MarginLeft, 0, graphScreenWidth, graphScreenHeight);
  134. RectangleF graphSpace = ScreenToGraphSpace (drawBounds);
  135. foreach (var s in Series.ToArray ()) {
  136. s.DrawSeries (this, drawBounds, graphSpace);
  137. // If a series changes the graph color reset it
  138. SetDriverColorToGraphColor ();
  139. }
  140. SetDriverColorToGraphColor ();
  141. // Draw 'after' annotations
  142. foreach (var a in Annotations.ToArray ().Where (a => !a.BeforeSeries)) {
  143. a.Render (this);
  144. }
  145. }
  146. /// <summary>
  147. /// Sets the color attribute of <see cref="Application.Driver"/> to the <see cref="GraphColor"/>
  148. /// (if defined) or <see cref="ColorScheme"/> otherwise.
  149. /// </summary>
  150. public void SetDriverColorToGraphColor ()
  151. {
  152. Driver.SetAttribute (GraphColor ?? (GetNormalColor ()));
  153. }
  154. /// <summary>
  155. /// Returns the section of the graph that is represented by the given
  156. /// screen position
  157. /// </summary>
  158. /// <param name="col"></param>
  159. /// <param name="row"></param>
  160. /// <returns></returns>
  161. public RectangleF ScreenToGraphSpace (int col, int row)
  162. {
  163. return new RectangleF (
  164. ScrollOffset.X + ((col - MarginLeft) * CellSize.X),
  165. ScrollOffset.Y + ((Bounds.Height - (row + MarginBottom + 1)) * CellSize.Y),
  166. CellSize.X, CellSize.Y);
  167. }
  168. /// <summary>
  169. /// Returns the section of the graph that is represented by the screen area
  170. /// </summary>
  171. /// <param name="screenArea"></param>
  172. /// <returns></returns>
  173. public RectangleF ScreenToGraphSpace (Rect screenArea)
  174. {
  175. // get position of the bottom left
  176. var pos = ScreenToGraphSpace (screenArea.Left, screenArea.Bottom - 1);
  177. return new RectangleF (pos.X, pos.Y, screenArea.Width * CellSize.X, screenArea.Height * CellSize.Y);
  178. }
  179. /// <summary>
  180. /// Calculates the screen location for a given point in graph space.
  181. /// Bear in mind these be off screen
  182. /// </summary>
  183. /// <param name="location">Point in graph space that may or may not be represented in the
  184. /// visible area of graph currently presented. E.g. 0,0 for origin</param>
  185. /// <returns>Screen position (Column/Row) which would be used to render the graph <paramref name="location"/>.
  186. /// Note that this can be outside the current client area of the control</returns>
  187. public Point GraphSpaceToScreen (PointF location)
  188. {
  189. return new Point (
  190. (int)((location.X - ScrollOffset.X) / CellSize.X) + (int)MarginLeft,
  191. // screen coordinates are top down while graph coordinates are bottom up
  192. (Bounds.Height - 1) - (int)MarginBottom - (int)((location.Y - ScrollOffset.Y) / CellSize.Y)
  193. );
  194. }
  195. /// <inheritdoc/>
  196. /// <remarks>Also ensures that cursor is invisible after entering the <see cref="GraphView"/>.</remarks>
  197. public override bool OnEnter (View view)
  198. {
  199. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  200. return base.OnEnter (view);
  201. }
  202. /// <summary>
  203. /// Scrolls the graph up 1 page
  204. /// </summary>
  205. public void PageUp ()
  206. {
  207. Scroll (0, CellSize.Y * Bounds.Height);
  208. }
  209. /// <summary>
  210. /// Scrolls the graph down 1 page
  211. /// </summary>
  212. public void PageDown ()
  213. {
  214. Scroll (0, -1 * CellSize.Y * Bounds.Height);
  215. }
  216. /// <summary>
  217. /// Scrolls the view by a given number of units in graph space.
  218. /// See <see cref="CellSize"/> to translate this into rows/cols
  219. /// </summary>
  220. /// <param name="offsetX"></param>
  221. /// <param name="offsetY"></param>
  222. public void Scroll (float offsetX, float offsetY)
  223. {
  224. ScrollOffset = new PointF (
  225. ScrollOffset.X + offsetX,
  226. ScrollOffset.Y + offsetY);
  227. SetNeedsDisplay ();
  228. }
  229. #region Bresenham's line algorithm
  230. // https://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#C.23
  231. int ipart (decimal x) { return (int)x; }
  232. decimal fpart (decimal x)
  233. {
  234. if (x < 0) return (1 - (x - Math.Floor (x)));
  235. return (x - Math.Floor (x));
  236. }
  237. /// <summary>
  238. /// Draws a line between two points in screen space. Can be diagonals.
  239. /// </summary>
  240. /// <param name="start"></param>
  241. /// <param name="end"></param>
  242. /// <param name="symbol">The symbol to use for the line</param>
  243. public void DrawLine (Point start, Point end, Rune symbol)
  244. {
  245. if (Equals (start, end)) {
  246. return;
  247. }
  248. int x0 = start.X;
  249. int y0 = start.Y;
  250. int x1 = end.X;
  251. int y1 = end.Y;
  252. int dx = Math.Abs (x1 - x0), sx = x0 < x1 ? 1 : -1;
  253. int dy = Math.Abs (y1 - y0), sy = y0 < y1 ? 1 : -1;
  254. int err = (dx > dy ? dx : -dy) / 2, e2;
  255. while (true) {
  256. AddRune (x0, y0, symbol);
  257. if (x0 == x1 && y0 == y1) break;
  258. e2 = err;
  259. if (e2 > -dx) { err -= dy; x0 += sx; }
  260. if (e2 < dy) { err += dx; y0 += sy; }
  261. }
  262. }
  263. #endregion
  264. }
  265. }