OutputBufferImpl.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 (ReferenceEquals (_clip, value))
  76. {
  77. return;
  78. }
  79. _clip = value;
  80. // Don't ever let Clip be bigger than Screen
  81. _clip?.Intersect (Screen);
  82. }
  83. }
  84. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  85. /// <remarks>
  86. /// <para>
  87. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  88. /// <paramref name="rune"/> required, even if the new column value is outside the <see cref="Clip"/> or screen
  89. /// dimensions defined by <see cref="Cols"/>.
  90. /// </para>
  91. /// <para>
  92. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  93. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  94. /// will be added instead.
  95. /// </para>
  96. /// </remarks>
  97. /// <param name="rune">Text to add.</param>
  98. public void AddRune (Rune rune) { AddStr (rune.ToString ()); }
  99. /// <summary>
  100. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  101. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  102. /// </summary>
  103. /// <param name="c">Character to add.</param>
  104. public void AddRune (char c) { AddRune (new Rune (c)); }
  105. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  106. /// <remarks>
  107. /// <para>
  108. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  109. /// <paramref name="str"/> required, unless the new column value is outside the <see cref="Clip"/> or screen
  110. /// dimensions defined by <see cref="Cols"/>.
  111. /// </para>
  112. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  113. /// </remarks>
  114. /// <param name="str">String.</param>
  115. public void AddStr (string str)
  116. {
  117. foreach (string grapheme in GraphemeHelper.GetGraphemes (str))
  118. {
  119. AddGrapheme (grapheme);
  120. }
  121. }
  122. /// <summary>
  123. /// Adds a single grapheme to the display at the current cursor position.
  124. /// </summary>
  125. /// <param name="grapheme">The grapheme to add.</param>
  126. private void AddGrapheme (string grapheme)
  127. {
  128. if (Contents is null)
  129. {
  130. return;
  131. }
  132. Clip ??= new (Screen);
  133. Rectangle clipRect = Clip!.GetBounds ();
  134. int printableGraphemeWidth = -1;
  135. lock (Contents)
  136. {
  137. if (IsValidLocation (grapheme, Col, Row))
  138. {
  139. // Set attribute and mark dirty for current cell
  140. SetAttributeAndDirty (Col, Row);
  141. InvalidateOverlappedWideGlyph (Col, Row);
  142. string printableGrapheme = grapheme.MakePrintable ();
  143. printableGraphemeWidth = printableGrapheme.GetColumns ();
  144. WriteGraphemeByWidth (Col, Row, printableGrapheme, printableGraphemeWidth, clipRect);
  145. DirtyLines [Row] = true;
  146. }
  147. // Always advance cursor (even if location was invalid)
  148. // Keep Col/Row updates inside the lock to prevent race conditions
  149. Col++;
  150. if (printableGraphemeWidth > 1)
  151. {
  152. // Skip the second column of a wide character
  153. // IMPORTANT: We do NOT modify column N+1's IsDirty or Attribute here.
  154. // See: https://github.com/gui-cs/Terminal.Gui/issues/4258
  155. Col++;
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// INTERNAL: Helper to set the attribute and mark the cell as dirty.
  161. /// </summary>
  162. /// <param name="col">The column.</param>
  163. /// <param name="row">The row.</param>
  164. private void SetAttributeAndDirty (int col, int row)
  165. {
  166. Contents! [row, col].Attribute = CurrentAttribute;
  167. Contents [row, col].IsDirty = true;
  168. }
  169. /// <summary>
  170. /// INTERNAL: If we're writing at an odd column and there's a wide glyph to our left,
  171. /// invalidate it since we're overwriting the second half.
  172. /// </summary>
  173. /// <param name="col">The column.</param>
  174. /// <param name="row">The row.</param>
  175. private void InvalidateOverlappedWideGlyph (int col, int row)
  176. {
  177. if (col > 0 && Contents! [row, col - 1].Grapheme.GetColumns () > 1)
  178. {
  179. Contents [row, col - 1].Grapheme = Rune.ReplacementChar.ToString ();
  180. Contents [row, col - 1].IsDirty = true;
  181. }
  182. }
  183. /// <summary>
  184. /// INTERNAL: Writes a Grapheme to the buffer based on its width (0, 1, or 2 columns).
  185. /// </summary>
  186. /// <param name="col">The column.</param>
  187. /// <param name="row">The row.</param>
  188. /// <param name="text">The printable text to write.</param>
  189. /// <param name="textWidth">The column width of the text.</param>
  190. /// <param name="clipRect">The clipping rectangle.</param>
  191. private void WriteGraphemeByWidth (int col, int row, string text, int textWidth, Rectangle clipRect)
  192. {
  193. switch (textWidth)
  194. {
  195. case 0:
  196. case 1:
  197. WriteGrapheme (col, row, text, clipRect);
  198. break;
  199. case 2:
  200. WriteWideGrapheme (col, row, text);
  201. break;
  202. default:
  203. // Negative width or non-spacing character (shouldn't normally occur)
  204. Contents! [row, col].Grapheme = " ";
  205. Contents [row, col].IsDirty = false;
  206. break;
  207. }
  208. }
  209. /// <summary>
  210. /// INTERNAL: Writes a (0 or 1 column wide) Grapheme.
  211. /// </summary>
  212. /// <param name="col">The column.</param>
  213. /// <param name="row">The row.</param>
  214. /// <param name="grapheme">The single-width Grapheme to write.</param>
  215. /// <param name="clipRect">The clipping rectangle.</param>
  216. private void WriteGrapheme (int col, int row, string grapheme, Rectangle clipRect)
  217. {
  218. Debug.Assert (grapheme.GetColumns () < 2);
  219. Contents! [row, col].Grapheme = grapheme;
  220. // Mark the next cell as dirty to ensure proper rendering of adjacent content
  221. if (col < clipRect.Right - 1 && col + 1 < Cols)
  222. {
  223. Contents [row, col + 1].IsDirty = true;
  224. }
  225. }
  226. /// <summary>
  227. /// INTERNAL: Writes a wide Grapheme (2 columns wide) handling clipping and partial overlap cases.
  228. /// </summary>
  229. /// <param name="col">The column.</param>
  230. /// <param name="row">The row.</param>
  231. /// <param name="grapheme">The wide Grapheme to write.</param>
  232. private void WriteWideGrapheme (int col, int row, string grapheme)
  233. {
  234. Debug.Assert (grapheme.GetColumns () == 2);
  235. if (!Clip!.Contains (col + 1, row))
  236. {
  237. // Second column is outside clip - can't fit wide char here
  238. Contents! [row, col].Grapheme = Rune.ReplacementChar.ToString ();
  239. }
  240. else if (!Clip.Contains (col, row))
  241. {
  242. // First column is outside clip but second isn't
  243. // Mark second column as replacement to indicate partial overlap
  244. if (col + 1 < Cols)
  245. {
  246. Contents! [row, col + 1].Grapheme = Rune.ReplacementChar.ToString ();
  247. Contents! [row, col + 1].IsDirty = true;
  248. }
  249. }
  250. else
  251. {
  252. // Both columns are in bounds - write the wide character
  253. // It will naturally render across both columns when output to the terminal
  254. Contents! [row, col].Grapheme = grapheme;
  255. // DO NOT modify column N+1 here!
  256. // The wide glyph will naturally render across both columns.
  257. // If we set column N+1 to replacement char, we would overwrite
  258. // any content that was intentionally drawn there (like borders at odd columns).
  259. // See: https://github.com/gui-cs/Terminal.Gui/issues/4258
  260. }
  261. }
  262. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  263. public void ClearContents ()
  264. {
  265. Contents = new Cell [Rows, Cols];
  266. // CONCURRENCY: Unsynchronized access to Clip isn't safe.
  267. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  268. Clip = new (Screen);
  269. DirtyLines = new bool [Rows];
  270. lock (Contents)
  271. {
  272. for (var row = 0; row < Rows; row++)
  273. {
  274. for (var c = 0; c < Cols; c++)
  275. {
  276. Contents [row, c] = new ()
  277. {
  278. Grapheme = " ",
  279. Attribute = new Attribute (Color.White, Color.Black),
  280. IsDirty = true
  281. };
  282. }
  283. DirtyLines [row] = true;
  284. }
  285. }
  286. }
  287. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  288. /// <param name="text">Used to determine if one or two columns are required.</param>
  289. /// <param name="col">The column.</param>
  290. /// <param name="row">The row.</param>
  291. /// <returns>
  292. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  293. /// <see langword="true"/> otherwise.
  294. /// </returns>
  295. public bool IsValidLocation (string text, int col, int row)
  296. {
  297. int textWidth = text.GetColumns ();
  298. return col >= 0 && row >= 0 && col + textWidth <= Cols && row < Rows && Clip!.Contains (col, row);
  299. }
  300. /// <inheritdoc/>
  301. public void SetSize (int cols, int rows)
  302. {
  303. Cols = cols;
  304. Rows = rows;
  305. ClearContents ();
  306. }
  307. /// <inheritdoc/>
  308. public void FillRect (Rectangle rect, Rune rune)
  309. {
  310. Rectangle clipBounds = Clip?.GetBounds () ?? Screen;
  311. // BUGBUG: This should be a method on Region
  312. rect = Rectangle.Intersect (rect, clipBounds);
  313. lock (Contents!)
  314. {
  315. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  316. {
  317. for (int c = rect.X; c < rect.X + rect.Width; c++)
  318. {
  319. if (!IsValidLocation (rune.ToString (), c, r))
  320. {
  321. continue;
  322. }
  323. // We could call AddGrapheme here, but that would acquire the lock again.
  324. // So we inline the logic instead.
  325. SetAttributeAndDirty (c, r);
  326. InvalidateOverlappedWideGlyph (c, r);
  327. string grapheme = rune != default (Rune) ? rune.ToString () : " ";
  328. WriteGraphemeByWidth (c, r, grapheme, grapheme.GetColumns (), clipBounds);
  329. }
  330. }
  331. }
  332. }
  333. /// <inheritdoc/>
  334. public void FillRect (Rectangle rect, char rune)
  335. {
  336. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  337. {
  338. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  339. {
  340. Move (x, y);
  341. AddRune (rune);
  342. }
  343. }
  344. }
  345. /// <summary>
  346. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  347. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  348. /// </summary>
  349. /// <remarks>
  350. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  351. /// <para>
  352. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  353. /// <see cref="Rows"/>, the method still sets those properties.
  354. /// </para>
  355. /// </remarks>
  356. /// <param name="col">Column to move to.</param>
  357. /// <param name="row">Row to move to.</param>
  358. public void Move (int col, int row)
  359. {
  360. Col = col;
  361. Row = row;
  362. }
  363. }