OutputBufferImpl.cs 14 KB

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