OutputBufferImpl.cs 16 KB

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