OutputBufferImpl.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. /// <inheritdoc/>
  58. public bool [] DirtyLines { get; set; } = [];
  59. // QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
  60. /// <summary>Gets the location and size of the terminal screen.</summary>
  61. internal Rectangle Screen => new (0, 0, Cols, Rows);
  62. private Region? _clip;
  63. /// <summary>
  64. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  65. /// to.
  66. /// </summary>
  67. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  68. public Region? Clip
  69. {
  70. get => _clip;
  71. set
  72. {
  73. if (_clip == value)
  74. {
  75. return;
  76. }
  77. _clip = value;
  78. // Don't ever let Clip be bigger than Screen
  79. if (_clip is { })
  80. {
  81. _clip.Intersect (Screen);
  82. }
  83. }
  84. }
  85. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  86. /// <remarks>
  87. /// <para>
  88. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  89. /// <paramref name="rune"/> required, even if the new column value is outside of the <see cref="Clip"/> or screen
  90. /// dimensions defined by <see cref="Cols"/>.
  91. /// </para>
  92. /// <para>
  93. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  94. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  95. /// will be added instead.
  96. /// </para>
  97. /// </remarks>
  98. /// <param name="rune">Rune to add.</param>
  99. public void AddRune (Rune rune)
  100. {
  101. int runeWidth = -1;
  102. bool validLocation = IsValidLocation (rune, Col, Row);
  103. if (Contents is null)
  104. {
  105. return;
  106. }
  107. Clip ??= new (Screen);
  108. Rectangle clipRect = Clip!.GetBounds ();
  109. if (validLocation)
  110. {
  111. rune = rune.MakePrintable ();
  112. runeWidth = rune.GetColumns ();
  113. lock (Contents)
  114. {
  115. if (runeWidth == 0 && rune.IsCombiningMark ())
  116. {
  117. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  118. // compatible with the driver architecture. Any CMs (except in the first col)
  119. // are correctly combined with the base char, but are ALSO treated as 1 column
  120. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  121. //
  122. // Until this is addressed (see Issue #), we do our best by
  123. // a) Attempting to normalize any CM with the base char to it's left
  124. // b) Ignoring any CMs that don't normalize
  125. if (Col > 0)
  126. {
  127. if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
  128. {
  129. // Just add this mark to the list
  130. Contents [Row, Col - 1].AddCombiningMark (rune);
  131. // Ignore. Don't move to next column (let the driver figure out what to do).
  132. }
  133. else
  134. {
  135. // Attempt to normalize the cell to our left combined with this mark
  136. string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
  137. // Normalize to Form C (Canonical Composition)
  138. string normalized = combined.Normalize (NormalizationForm.FormC);
  139. if (normalized.Length == 1)
  140. {
  141. // It normalized! We can just set the Cell to the left with the
  142. // normalized codepoint
  143. Contents [Row, Col - 1].Rune = (Rune)normalized [0];
  144. // Ignore. Don't move to next column because we're already there
  145. }
  146. else
  147. {
  148. // It didn't normalize. Add it to the Cell to left's CM list
  149. Contents [Row, Col - 1].AddCombiningMark (rune);
  150. // Ignore. Don't move to next column (let the driver figure out what to do).
  151. }
  152. }
  153. Contents [Row, Col - 1].Attribute = CurrentAttribute;
  154. Contents [Row, Col - 1].IsDirty = true;
  155. }
  156. else
  157. {
  158. // Most drivers will render a combining mark at col 0 as the mark
  159. Contents [Row, Col].Rune = rune;
  160. Contents [Row, Col].Attribute = CurrentAttribute;
  161. Contents [Row, Col].IsDirty = true;
  162. Col++;
  163. }
  164. }
  165. else
  166. {
  167. Contents [Row, Col].Attribute = CurrentAttribute;
  168. Contents [Row, Col].IsDirty = true;
  169. if (Col > 0)
  170. {
  171. // Check if cell to left has a wide glyph
  172. if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
  173. {
  174. // Invalidate cell to left
  175. Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
  176. Contents [Row, Col - 1].IsDirty = true;
  177. }
  178. }
  179. if (runeWidth < 1)
  180. {
  181. Contents [Row, Col].Rune = Rune.ReplacementChar;
  182. }
  183. else if (runeWidth == 1)
  184. {
  185. Contents [Row, Col].Rune = rune;
  186. if (Col < clipRect.Right - 1)
  187. {
  188. Contents [Row, Col + 1].IsDirty = true;
  189. }
  190. }
  191. else if (runeWidth == 2)
  192. {
  193. if (!Clip.Contains (Col + 1, Row))
  194. {
  195. // We're at the right edge of the clip, so we can't display a wide character.
  196. // TODO: Figure out if it is better to show a replacement character or ' '
  197. Contents [Row, Col].Rune = Rune.ReplacementChar;
  198. }
  199. else if (!Clip.Contains (Col, Row))
  200. {
  201. // Our 1st column is outside the clip, so we can't display a wide character.
  202. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  203. }
  204. else
  205. {
  206. Contents [Row, Col].Rune = rune;
  207. if (Col < clipRect.Right - 1)
  208. {
  209. // Invalidate cell to right so that it doesn't get drawn
  210. // TODO: Figure out if it is better to show a replacement character or ' '
  211. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  212. Contents [Row, Col + 1].IsDirty = true;
  213. }
  214. }
  215. }
  216. else
  217. {
  218. // This is a non-spacing character, so we don't need to do anything
  219. Contents [Row, Col].Rune = (Rune)' ';
  220. Contents [Row, Col].IsDirty = false;
  221. }
  222. DirtyLines [Row] = true;
  223. }
  224. }
  225. }
  226. if (runeWidth is < 0 or > 0)
  227. {
  228. Col++;
  229. }
  230. if (runeWidth > 1)
  231. {
  232. Debug.Assert (runeWidth <= 2);
  233. if (validLocation && Col < clipRect.Right)
  234. {
  235. lock (Contents!)
  236. {
  237. // This is a double-width character, and we are not at the end of the line.
  238. // Col now points to the second column of the character. Ensure it doesn't
  239. // Get rendered.
  240. Contents [Row, Col].IsDirty = false;
  241. Contents [Row, Col].Attribute = CurrentAttribute;
  242. // TODO: Determine if we should wipe this out (for now now)
  243. //Contents [Row, Col].Rune = (Rune)' ';
  244. }
  245. }
  246. Col++;
  247. }
  248. }
  249. /// <summary>
  250. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  251. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  252. /// </summary>
  253. /// <param name="c">Character to add.</param>
  254. public void AddRune (char c) { AddRune (new Rune (c)); }
  255. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  256. /// <remarks>
  257. /// <para>
  258. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  259. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="Clip"/> or screen
  260. /// dimensions defined by <see cref="Cols"/>.
  261. /// </para>
  262. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  263. /// </remarks>
  264. /// <param name="str">String.</param>
  265. public void AddStr (string str)
  266. {
  267. List<Rune> runes = str.EnumerateRunes ().ToList ();
  268. for (var i = 0; i < runes.Count; i++)
  269. {
  270. AddRune (runes [i]);
  271. }
  272. }
  273. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  274. public void ClearContents ()
  275. {
  276. Contents = new Cell [Rows, Cols];
  277. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  278. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  279. Clip = new (Screen);
  280. DirtyLines = new bool [Rows];
  281. lock (Contents)
  282. {
  283. for (var row = 0; row < Rows; row++)
  284. {
  285. for (var c = 0; c < Cols; c++)
  286. {
  287. Contents [row, c] = new ()
  288. {
  289. Rune = (Rune)' ',
  290. Attribute = new Attribute (Color.White, Color.Black),
  291. IsDirty = true
  292. };
  293. }
  294. DirtyLines [row] = true;
  295. }
  296. }
  297. // TODO: Who uses this and why? I am removing for now - this class is a state class not an events class
  298. //ClearedContents?.Invoke (this, EventArgs.Empty);
  299. }
  300. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  301. /// <param name="rune">Used to determine if one or two columns are required.</param>
  302. /// <param name="col">The column.</param>
  303. /// <param name="row">The row.</param>
  304. /// <returns>
  305. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  306. /// <see langword="true"/> otherwise.
  307. /// </returns>
  308. public bool IsValidLocation (Rune rune, int col, int row)
  309. {
  310. if (rune.GetColumns () < 2)
  311. {
  312. return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row);
  313. }
  314. return Clip!.Contains (col, row) || Clip!.Contains (col + 1, row);
  315. }
  316. /// <inheritdoc/>
  317. public void SetSize (int cols, int rows)
  318. {
  319. Cols = cols;
  320. Rows = rows;
  321. ClearContents ();
  322. }
  323. /// <inheritdoc/>
  324. public void FillRect (Rectangle rect, Rune rune)
  325. {
  326. // BUGBUG: This should be a method on Region
  327. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  328. lock (Contents!)
  329. {
  330. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  331. {
  332. for (int c = rect.X; c < rect.X + rect.Width; c++)
  333. {
  334. if (!IsValidLocation (rune, c, r))
  335. {
  336. continue;
  337. }
  338. Contents [r, c] = new ()
  339. {
  340. Rune = rune != default (Rune) ? rune : (Rune)' ',
  341. Attribute = CurrentAttribute, IsDirty = true
  342. };
  343. }
  344. }
  345. }
  346. }
  347. /// <inheritdoc/>
  348. public void FillRect (Rectangle rect, char rune)
  349. {
  350. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  351. {
  352. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  353. {
  354. Move (x, y);
  355. AddRune (rune);
  356. }
  357. }
  358. }
  359. // TODO: Make internal once Menu is upgraded
  360. /// <summary>
  361. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  362. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  363. /// </summary>
  364. /// <remarks>
  365. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  366. /// <para>
  367. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  368. /// <see cref="Rows"/>, the method still sets those properties.
  369. /// </para>
  370. /// </remarks>
  371. /// <param name="col">Column to move to.</param>
  372. /// <param name="row">Row to move to.</param>
  373. public virtual void Move (int col, int row)
  374. {
  375. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  376. Col = col;
  377. Row = row;
  378. }
  379. }