OutputBufferImpl.cs 15 KB

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