OutputBufferImpl.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. // IMPORTANT: We do NOT modify column N+1's IsDirty or Attribute here.
  160. // See: https://github.com/gui-cs/Terminal.Gui/issues/4258
  161. Col++;
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// INTERNAL: Helper to set the attribute and mark the cell as dirty.
  167. /// </summary>
  168. /// <param name="col">The column.</param>
  169. /// <param name="row">The row.</param>
  170. private void SetAttributeAndDirty (int col, int row)
  171. {
  172. Contents! [row, col].Attribute = CurrentAttribute;
  173. Contents [row, col].IsDirty = true;
  174. }
  175. /// <summary>
  176. /// INTERNAL: If we're writing at an odd column and there's a wide glyph to our left,
  177. /// invalidate it since we're overwriting the second half.
  178. /// </summary>
  179. /// <param name="col">The column.</param>
  180. /// <param name="row">The row.</param>
  181. private void InvalidateOverlappedWideGlyph (int col, int row)
  182. {
  183. if (col > 0 && Contents! [row, col - 1].Grapheme.GetColumns () > 1)
  184. {
  185. Contents [row, col - 1].Grapheme = _column1ReplacementChar.ToString ();
  186. Contents [row, col - 1].IsDirty = true;
  187. }
  188. }
  189. /// <summary>
  190. /// INTERNAL: Writes a Grapheme to the buffer based on its width (0, 1, or 2 columns).
  191. /// </summary>
  192. /// <param name="col">The column.</param>
  193. /// <param name="row">The row.</param>
  194. /// <param name="text">The printable text to write.</param>
  195. /// <param name="textWidth">The column width of the text.</param>
  196. /// <param name="clipRect">The clipping rectangle.</param>
  197. private void WriteGraphemeByWidth (int col, int row, string text, int textWidth, Rectangle clipRect)
  198. {
  199. switch (textWidth)
  200. {
  201. case 0:
  202. case 1:
  203. WriteGrapheme (col, row, text, clipRect);
  204. break;
  205. case 2:
  206. WriteWideGrapheme (col, row, text);
  207. break;
  208. default:
  209. // Negative width or non-spacing character (shouldn't normally occur)
  210. Contents! [row, col].Grapheme = " ";
  211. Contents [row, col].IsDirty = false;
  212. break;
  213. }
  214. }
  215. /// <summary>
  216. /// INTERNAL: Writes a (0 or 1 column wide) Grapheme.
  217. /// </summary>
  218. /// <param name="col">The column.</param>
  219. /// <param name="row">The row.</param>
  220. /// <param name="grapheme">The single-width Grapheme to write.</param>
  221. /// <param name="clipRect">The clipping rectangle.</param>
  222. private void WriteGrapheme (int col, int row, string grapheme, Rectangle clipRect)
  223. {
  224. Debug.Assert (grapheme.GetColumns () < 2);
  225. Contents! [row, col].Grapheme = grapheme;
  226. // Mark the next cell as dirty to ensure proper rendering of adjacent content
  227. if (col < clipRect.Right - 1 && col + 1 < Cols)
  228. {
  229. Contents [row, col + 1].IsDirty = true;
  230. }
  231. }
  232. /// <summary>
  233. /// INTERNAL: Writes a wide Grapheme (2 columns wide) handling clipping and partial overlap cases.
  234. /// </summary>
  235. /// <param name="col">The column.</param>
  236. /// <param name="row">The row.</param>
  237. /// <param name="grapheme">The wide Grapheme to write.</param>
  238. private void WriteWideGrapheme (int col, int row, string grapheme)
  239. {
  240. Debug.Assert (grapheme.GetColumns () == 2);
  241. if (!Clip!.Contains (col + 1, row))
  242. {
  243. // Second column is outside clip - can't fit wide char here
  244. Contents! [row, col].Grapheme = _column1ReplacementChar.ToString ();
  245. }
  246. else
  247. {
  248. // Both columns are in bounds - write the wide character
  249. // It will naturally render across both columns when output to the terminal
  250. Contents! [row, col].Grapheme = grapheme;
  251. // DO NOT modify column N+1 here!
  252. // The wide glyph will naturally render across both columns.
  253. // If we set column N+1 to replacement char, we would overwrite
  254. // any content that was intentionally drawn there (like borders at odd columns).
  255. // See: https://github.com/gui-cs/Terminal.Gui/issues/4258
  256. }
  257. }
  258. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  259. public void ClearContents ()
  260. {
  261. Contents = new Cell [Rows, Cols];
  262. // CONCURRENCY: Unsynchronized access to Clip isn't safe.
  263. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  264. Clip = new (Screen);
  265. DirtyLines = new bool [Rows];
  266. lock (Contents)
  267. {
  268. for (var row = 0; row < Rows; row++)
  269. {
  270. for (var c = 0; c < Cols; c++)
  271. {
  272. Contents [row, c] = new ()
  273. {
  274. Grapheme = " ",
  275. Attribute = new Attribute (Color.White, Color.Black),
  276. IsDirty = true
  277. };
  278. }
  279. DirtyLines [row] = true;
  280. }
  281. }
  282. }
  283. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  284. /// <param name="text">Used to determine if one or two columns are required.</param>
  285. /// <param name="col">The column.</param>
  286. /// <param name="row">The row.</param>
  287. /// <returns>
  288. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  289. /// <see langword="true"/> otherwise.
  290. /// </returns>
  291. public bool IsValidLocation (string text, int col, int row)
  292. {
  293. int textWidth = text.GetColumns ();
  294. return col >= 0 && row >= 0 && col + textWidth <= Cols && row < Rows && Clip!.Contains (col, row);
  295. }
  296. /// <inheritdoc/>
  297. public void SetSize (int cols, int rows)
  298. {
  299. Cols = cols;
  300. Rows = rows;
  301. ClearContents ();
  302. }
  303. /// <inheritdoc/>
  304. public void FillRect (Rectangle rect, Rune rune)
  305. {
  306. Rectangle clipBounds = Clip?.GetBounds () ?? Screen;
  307. // BUGBUG: This should be a method on Region
  308. rect = Rectangle.Intersect (rect, clipBounds);
  309. lock (Contents!)
  310. {
  311. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  312. {
  313. for (int c = rect.X; c < rect.X + rect.Width; c++)
  314. {
  315. if (!IsValidLocation (rune.ToString (), c, r))
  316. {
  317. continue;
  318. }
  319. // We could call AddGrapheme here, but that would acquire the lock again.
  320. // So we inline the logic instead.
  321. SetAttributeAndDirty (c, r);
  322. InvalidateOverlappedWideGlyph (c, r);
  323. string grapheme = rune != default (Rune) ? rune.ToString () : " ";
  324. WriteGraphemeByWidth (c, r, grapheme, grapheme.GetColumns (), clipBounds);
  325. }
  326. }
  327. }
  328. }
  329. /// <inheritdoc/>
  330. public void FillRect (Rectangle rect, char rune)
  331. {
  332. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  333. {
  334. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  335. {
  336. Move (x, y);
  337. AddRune (rune);
  338. }
  339. }
  340. }
  341. /// <summary>
  342. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  343. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  344. /// </summary>
  345. /// <remarks>
  346. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  347. /// <para>
  348. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  349. /// <see cref="Rows"/>, the method still sets those properties.
  350. /// </para>
  351. /// </remarks>
  352. /// <param name="col">Column to move to.</param>
  353. /// <param name="row">Row to move to.</param>
  354. public void Move (int col, int row)
  355. {
  356. Col = col;
  357. Row = row;
  358. }
  359. }