OutputBufferImpl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. using System.Diagnostics;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Stores the desired output state for the whole application. This is updated during
  5. /// draw operations before being flushed to the console as part of the main loop.
  6. /// operation
  7. /// </summary>
  8. public class OutputBufferImpl : IOutputBuffer
  9. {
  10. /// <summary>
  11. /// The contents of the application output. The driver outputs this buffer to the terminal when
  12. /// UpdateScreen is called.
  13. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  14. /// </summary>
  15. public Cell [,]? Contents { get; set; } = new Cell[0, 0];
  16. private int _cols;
  17. private int _rows;
  18. /// <summary>
  19. /// The <see cref="Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or <see cref="AddStr"/>
  20. /// call.
  21. /// </summary>
  22. public Attribute CurrentAttribute { get; set; }
  23. /// <summary>The leftmost column in the terminal.</summary>
  24. public virtual int Left { get; set; } = 0;
  25. /// <summary>
  26. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  27. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  28. /// </summary>
  29. public int Row { get; private set; }
  30. /// <summary>
  31. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  32. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  33. /// </summary>
  34. public int Col { get; private set; }
  35. /// <summary>The number of rows visible in the terminal.</summary>
  36. public int Rows
  37. {
  38. get => _rows;
  39. set
  40. {
  41. _rows = value;
  42. ClearContents ();
  43. }
  44. }
  45. /// <summary>The number of columns visible in the terminal.</summary>
  46. public int Cols
  47. {
  48. get => _cols;
  49. set
  50. {
  51. _cols = value;
  52. ClearContents ();
  53. }
  54. }
  55. /// <summary>The topmost row in the terminal.</summary>
  56. public virtual int Top { get; set; } = 0;
  57. /// <summary>
  58. /// Indicates which lines have been modified and need to be redrawn.
  59. /// </summary>
  60. public bool [] DirtyLines { get; set; } = [];
  61. // QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
  62. /// <summary>Gets the location and size of the terminal screen.</summary>
  63. internal Rectangle Screen => new (0, 0, Cols, Rows);
  64. private Region? _clip;
  65. /// <summary>
  66. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  67. /// to.
  68. /// </summary>
  69. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  70. public Region? Clip
  71. {
  72. get => _clip;
  73. set
  74. {
  75. if (_clip == value)
  76. {
  77. return;
  78. }
  79. _clip = value;
  80. // Don't ever let Clip be bigger than Screen
  81. if (_clip is { })
  82. {
  83. _clip.Intersect (Screen);
  84. }
  85. }
  86. }
  87. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  88. /// <remarks>
  89. /// <para>
  90. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  91. /// <paramref name="rune"/> required, even if the new column value is outside of the <see cref="Clip"/> or screen
  92. /// dimensions defined by <see cref="Cols"/>.
  93. /// </para>
  94. /// <para>
  95. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  96. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  97. /// will be added instead.
  98. /// </para>
  99. /// </remarks>
  100. /// <param name="rune">Text to add.</param>
  101. public void AddRune (Rune rune) { AddStr (rune.ToString ()); }
  102. /// <summary>
  103. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  104. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  105. /// </summary>
  106. /// <param name="c">Character to add.</param>
  107. public void AddRune (char c) { AddRune (new Rune (c)); }
  108. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  109. /// <remarks>
  110. /// <para>
  111. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  112. /// <paramref name="str"/> required, unless the new column value is outside the <see cref="Clip"/> or screen
  113. /// dimensions defined by <see cref="Cols"/>.
  114. /// </para>
  115. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  116. /// </remarks>
  117. /// <param name="str">String.</param>
  118. public void AddStr (string str)
  119. {
  120. foreach (string grapheme in GraphemeHelper.GetGraphemes (str))
  121. {
  122. string text = grapheme;
  123. if (Contents is null)
  124. {
  125. return;
  126. }
  127. Clip ??= new (Screen);
  128. Rectangle clipRect = Clip!.GetBounds ();
  129. int textWidth = -1;
  130. bool validLocation = false;
  131. lock (Contents)
  132. {
  133. // Validate location inside the lock to prevent race conditions
  134. validLocation = IsValidLocation (text, Col, Row);
  135. if (validLocation)
  136. {
  137. text = text.MakePrintable ();
  138. textWidth = text.GetColumns ();
  139. Contents [Row, Col].Attribute = CurrentAttribute;
  140. Contents [Row, Col].IsDirty = true;
  141. if (Col > 0)
  142. {
  143. // Check if cell to left has a wide glyph
  144. if (Contents [Row, Col - 1].Grapheme.GetColumns () > 1)
  145. {
  146. // Invalidate cell to left
  147. Contents [Row, Col - 1].Grapheme = Rune.ReplacementChar.ToString ();
  148. Contents [Row, Col - 1].IsDirty = true;
  149. }
  150. }
  151. if (textWidth is 0 or 1)
  152. {
  153. Contents [Row, Col].Grapheme = text;
  154. if (Col < clipRect.Right - 1 && Col + 1 < Cols)
  155. {
  156. Contents [Row, Col + 1].IsDirty = true;
  157. }
  158. }
  159. else if (textWidth == 2)
  160. {
  161. if (!Clip.Contains (Col + 1, Row))
  162. {
  163. // We're at the right edge of the clip, so we can't display a wide character.
  164. Contents [Row, Col].Grapheme = Rune.ReplacementChar.ToString ();
  165. }
  166. else if (!Clip.Contains (Col, Row))
  167. {
  168. // Our 1st column is outside the clip, so we can't display a wide character.
  169. if (Col + 1 < Cols)
  170. {
  171. Contents [Row, Col + 1].Grapheme = Rune.ReplacementChar.ToString ();
  172. }
  173. }
  174. else
  175. {
  176. Contents [Row, Col].Grapheme = text;
  177. if (Col < clipRect.Right - 1 && Col + 1 < Cols)
  178. {
  179. // Invalidate cell to right so that it doesn't get drawn
  180. Contents [Row, Col + 1].Grapheme = Rune.ReplacementChar.ToString ();
  181. Contents [Row, Col + 1].IsDirty = true;
  182. }
  183. }
  184. }
  185. else
  186. {
  187. // This is a non-spacing character, so we don't need to do anything
  188. Contents [Row, Col].Grapheme = " ";
  189. Contents [Row, Col].IsDirty = false;
  190. }
  191. DirtyLines [Row] = true;
  192. }
  193. }
  194. Col++;
  195. if (textWidth > 1)
  196. {
  197. Debug.Assert (textWidth <= 2);
  198. if (validLocation)
  199. {
  200. lock (Contents!)
  201. {
  202. // Re-validate Col is still in bounds after increment
  203. if (Col < Cols && Row < Rows && Col < clipRect.Right)
  204. {
  205. // This is a double-width character, and we are not at the end of the line.
  206. // Col now points to the second column of the character. Ensure it doesn't
  207. // Get rendered.
  208. Contents [Row, Col].IsDirty = false;
  209. Contents [Row, Col].Attribute = CurrentAttribute;
  210. }
  211. }
  212. }
  213. Col++;
  214. }
  215. }
  216. }
  217. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  218. public void ClearContents ()
  219. {
  220. Contents = new Cell [Rows, Cols];
  221. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  222. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  223. Clip = new (Screen);
  224. DirtyLines = new bool [Rows];
  225. lock (Contents)
  226. {
  227. for (var row = 0; row < Rows; row++)
  228. {
  229. for (var c = 0; c < Cols; c++)
  230. {
  231. Contents [row, c] = new ()
  232. {
  233. Grapheme = " ",
  234. Attribute = new Attribute (Color.White, Color.Black),
  235. IsDirty = true
  236. };
  237. }
  238. DirtyLines [row] = true;
  239. }
  240. }
  241. // TODO: Who uses this and why? I am removing for now - this class is a state class not an events class
  242. //ClearedContents?.Invoke (this, EventArgs.Empty);
  243. }
  244. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  245. /// <param name="text">Used to determine if one or two columns are required.</param>
  246. /// <param name="col">The column.</param>
  247. /// <param name="row">The row.</param>
  248. /// <returns>
  249. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  250. /// <see langword="true"/> otherwise.
  251. /// </returns>
  252. public bool IsValidLocation (string text, int col, int row)
  253. {
  254. int textWidth = text.GetColumns ();
  255. return col >= 0 && row >= 0 && col + textWidth <= Cols && row < Rows && Clip!.Contains (col, row);
  256. }
  257. /// <inheritdoc/>
  258. public void SetSize (int cols, int rows)
  259. {
  260. Cols = cols;
  261. Rows = rows;
  262. ClearContents ();
  263. }
  264. /// <inheritdoc/>
  265. public void FillRect (Rectangle rect, Rune rune)
  266. {
  267. // BUGBUG: This should be a method on Region
  268. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  269. lock (Contents!)
  270. {
  271. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  272. {
  273. for (int c = rect.X; c < rect.X + rect.Width; c++)
  274. {
  275. if (!IsValidLocation (rune.ToString (), c, r))
  276. {
  277. continue;
  278. }
  279. Contents [r, c] = new ()
  280. {
  281. Grapheme = rune != default (Rune) ? rune.ToString () : " ",
  282. Attribute = CurrentAttribute, IsDirty = true
  283. };
  284. }
  285. }
  286. }
  287. }
  288. /// <inheritdoc/>
  289. public void FillRect (Rectangle rect, char rune)
  290. {
  291. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  292. {
  293. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  294. {
  295. Move (x, y);
  296. AddRune (rune);
  297. }
  298. }
  299. }
  300. // TODO: Make internal once Menu is upgraded
  301. /// <summary>
  302. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  303. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  304. /// </summary>
  305. /// <remarks>
  306. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  307. /// <para>
  308. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  309. /// <see cref="Rows"/>, the method still sets those properties.
  310. /// </para>
  311. /// </remarks>
  312. /// <param name="col">Column to move to.</param>
  313. /// <param name="row">Row to move to.</param>
  314. public virtual void Move (int col, int row)
  315. {
  316. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  317. Col = col;
  318. Row = row;
  319. }
  320. }