TextFormatter.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using NStack;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// Text alignment enumeration, controls how text is displayed.
  9. /// </summary>
  10. public enum TextAlignment {
  11. /// <summary>
  12. /// Aligns the text to the left of the frame.
  13. /// </summary>
  14. Left,
  15. /// <summary>
  16. /// Aligns the text to the right side of the frame.
  17. /// </summary>
  18. Right,
  19. /// <summary>
  20. /// Centers the text in the frame.
  21. /// </summary>
  22. Centered,
  23. /// <summary>
  24. /// Shows the text as justified text in the frame.
  25. /// </summary>
  26. Justified
  27. }
  28. /// <summary>
  29. /// Vertical text alignment enumeration, controls how text is displayed.
  30. /// </summary>
  31. public enum VerticalTextAlignment {
  32. /// <summary>
  33. /// Aligns the text to the top of the frame.
  34. /// </summary>
  35. Top,
  36. /// <summary>
  37. /// Aligns the text to the bottom of the frame.
  38. /// </summary>
  39. Bottom,
  40. /// <summary>
  41. /// Centers the text verticaly in the frame.
  42. /// </summary>
  43. Middle,
  44. /// <summary>
  45. /// Shows the text as justified text in the frame.
  46. /// </summary>
  47. Justified
  48. }
  49. /// TextDirection [H] = Horizontal [V] = Vertical
  50. /// =============
  51. /// LeftRight_TopBottom [H] Normal
  52. /// TopBottom_LeftRight [V] Normal
  53. ///
  54. /// RightLeft_TopBottom [H] Invert Text
  55. /// TopBottom_RightLeft [V] Invert Lines
  56. ///
  57. /// LeftRight_BottomTop [H] Invert Lines
  58. /// BottomTop_LeftRight [V] Invert Text
  59. ///
  60. /// RightLeft_BottomTop [H] Invert Text + Invert Lines
  61. /// BottomTop_RightLeft [V] Invert Text + Invert Lines
  62. ///
  63. /// <summary>
  64. /// Text direction enumeration, controls how text is displayed.
  65. /// </summary>
  66. public enum TextDirection {
  67. /// <summary>
  68. /// Normal horizontal direction.
  69. /// <code>HELLO<br/>WORLD</code>
  70. /// </summary>
  71. LeftRight_TopBottom,
  72. /// <summary>
  73. /// Normal vertical direction.
  74. /// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
  75. /// </summary>
  76. TopBottom_LeftRight,
  77. /// <summary>
  78. /// This is a horizontal direction. <br/> RTL
  79. /// <code>OLLEH<br/>DLROW</code>
  80. /// </summary>
  81. RightLeft_TopBottom,
  82. /// <summary>
  83. /// This is a vertical direction.
  84. /// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
  85. /// </summary>
  86. TopBottom_RightLeft,
  87. /// <summary>
  88. /// This is a horizontal direction.
  89. /// <code>WORLD<br/>HELLO</code>
  90. /// </summary>
  91. LeftRight_BottomTop,
  92. /// <summary>
  93. /// This is a vertical direction.
  94. /// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
  95. /// </summary>
  96. BottomTop_LeftRight,
  97. /// <summary>
  98. /// This is a horizontal direction.
  99. /// <code>DLROW<br/>OLLEH</code>
  100. /// </summary>
  101. RightLeft_BottomTop,
  102. /// <summary>
  103. /// This is a vertical direction.
  104. /// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
  105. /// </summary>
  106. BottomTop_RightLeft
  107. }
  108. /// <summary>
  109. /// Provides text formatting capabilities for console apps. Supports, hotkeys, horizontal alignment, multiple lines, and word-based line wrap.
  110. /// </summary>
  111. public class TextFormatter {
  112. List<ustring> lines = new List<ustring> ();
  113. ustring text;
  114. TextAlignment textAlignment;
  115. VerticalTextAlignment textVerticalAlignment;
  116. TextDirection textDirection;
  117. Attribute textColor = -1;
  118. bool needsFormat;
  119. Key hotKey;
  120. Size size;
  121. /// <summary>
  122. /// Event invoked when the <see cref="HotKey"/> is changed.
  123. /// </summary>
  124. public event Action<Key> HotKeyChanged;
  125. /// <summary>
  126. /// The text to be displayed. This text is never modified.
  127. /// </summary>
  128. public virtual ustring Text {
  129. get => text;
  130. set {
  131. text = value;
  132. if (text != null && text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.ConsoleWidth)) {
  133. // Provide a default size (width = length of longest line, height = 1)
  134. // TODO: It might makes more sense for the default to be width = length of first line?
  135. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  136. }
  137. NeedsFormat = true;
  138. }
  139. }
  140. /// <summary>
  141. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  142. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  143. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  144. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  145. /// </summary>
  146. public bool AutoSize { get; set; }
  147. /// <summary>
  148. /// Gets or sets a flag that determines whether <see cref="Text"/> will have trailing spaces preserved
  149. /// or not when <see cref="WordWrap"/> is enabled. If `true` any trailing spaces will be trimmed when
  150. /// either the <see cref="Text"/> property is changed or when <see cref="WordWrap"/> is set to `true`.
  151. /// The default is `false`.
  152. /// </summary>
  153. public bool PreserveTrailingSpaces { get; set; }
  154. /// <summary>
  155. /// Controls the horizontal text-alignment property.
  156. /// </summary>
  157. /// <value>The text alignment.</value>
  158. public TextAlignment Alignment {
  159. get => textAlignment;
  160. set {
  161. textAlignment = value;
  162. NeedsFormat = true;
  163. }
  164. }
  165. /// <summary>
  166. /// Controls the vertical text-alignment property.
  167. /// </summary>
  168. /// <value>The text vertical alignment.</value>
  169. public VerticalTextAlignment VerticalAlignment {
  170. get => textVerticalAlignment;
  171. set {
  172. textVerticalAlignment = value;
  173. NeedsFormat = true;
  174. }
  175. }
  176. /// <summary>
  177. /// Controls the text-direction property.
  178. /// </summary>
  179. /// <value>The text vertical alignment.</value>
  180. public TextDirection Direction {
  181. get => textDirection;
  182. set {
  183. textDirection = value;
  184. NeedsFormat = true;
  185. }
  186. }
  187. /// <summary>
  188. /// Check if it is a horizontal direction
  189. /// </summary>
  190. public static bool IsHorizontalDirection (TextDirection textDirection)
  191. {
  192. switch (textDirection) {
  193. case TextDirection.LeftRight_TopBottom:
  194. case TextDirection.LeftRight_BottomTop:
  195. case TextDirection.RightLeft_TopBottom:
  196. case TextDirection.RightLeft_BottomTop:
  197. return true;
  198. default:
  199. return false;
  200. }
  201. }
  202. /// <summary>
  203. /// Check if it is a vertical direction
  204. /// </summary>
  205. public static bool IsVerticalDirection (TextDirection textDirection)
  206. {
  207. switch (textDirection) {
  208. case TextDirection.TopBottom_LeftRight:
  209. case TextDirection.TopBottom_RightLeft:
  210. case TextDirection.BottomTop_LeftRight:
  211. case TextDirection.BottomTop_RightLeft:
  212. return true;
  213. default:
  214. return false;
  215. }
  216. }
  217. /// <summary>
  218. /// Check if it is Left to Right direction
  219. /// </summary>
  220. public static bool IsLeftToRight (TextDirection textDirection)
  221. {
  222. switch (textDirection) {
  223. case TextDirection.LeftRight_TopBottom:
  224. case TextDirection.LeftRight_BottomTop:
  225. return true;
  226. default:
  227. return false;
  228. }
  229. }
  230. /// <summary>
  231. /// Check if it is Top to Bottom direction
  232. /// </summary>
  233. public static bool IsTopToBottom (TextDirection textDirection)
  234. {
  235. switch (textDirection) {
  236. case TextDirection.TopBottom_LeftRight:
  237. case TextDirection.TopBottom_RightLeft:
  238. return true;
  239. default:
  240. return false;
  241. }
  242. }
  243. /// <summary>
  244. /// Gets or sets the size of the area the text will be constrained to when formatted.
  245. /// </summary>
  246. public Size Size {
  247. get => size;
  248. set {
  249. size = value;
  250. NeedsFormat = true;
  251. }
  252. }
  253. /// <summary>
  254. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  255. /// </summary>
  256. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  257. /// <summary>
  258. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  259. /// </summary>
  260. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  261. /// <summary>
  262. /// Gets the hotkey. Will be an upper case letter or digit.
  263. /// </summary>
  264. public Key HotKey {
  265. get => hotKey;
  266. internal set {
  267. if (hotKey != value) {
  268. var oldKey = hotKey;
  269. hotKey = value;
  270. HotKeyChanged?.Invoke (oldKey);
  271. }
  272. }
  273. }
  274. /// <summary>
  275. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  276. /// the underlying Rune to be identified as a "private use" Unicode character.
  277. /// </summary>HotKeyTagMask
  278. public uint HotKeyTagMask { get; set; } = 0x100000;
  279. /// <summary>
  280. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  281. /// </summary>
  282. public int CursorPosition { get; set; }
  283. /// <summary>
  284. /// Gets the formatted lines.
  285. /// </summary>
  286. /// <remarks>
  287. /// <para>
  288. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  289. /// <see cref="Format(ustring, int, bool, bool, bool, int, TextDirection)"/> will be called internally.
  290. /// </para>
  291. /// </remarks>
  292. public List<ustring> Lines {
  293. get {
  294. // With this check, we protect against subclasses with overrides of Text
  295. if (ustring.IsNullOrEmpty (Text) || Size.IsEmpty) {
  296. lines = new List<ustring> ();
  297. lines.Add (ustring.Empty);
  298. NeedsFormat = false;
  299. return lines;
  300. }
  301. if (NeedsFormat) {
  302. var shown_text = text;
  303. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out Key newHotKey)) {
  304. HotKey = newHotKey;
  305. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  306. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  307. }
  308. if (IsVerticalDirection (textDirection)) {
  309. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1);
  310. lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth,
  311. PreserveTrailingSpaces, 0, textDirection);
  312. if (!AutoSize) {
  313. colsWidth = GetMaxColsForWidth (lines, Size.Width);
  314. if (lines.Count > colsWidth) {
  315. lines.RemoveRange (colsWidth, lines.Count - colsWidth);
  316. }
  317. }
  318. } else {
  319. lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1,
  320. PreserveTrailingSpaces, 0, textDirection);
  321. if (!AutoSize && lines.Count > Size.Height) {
  322. lines.RemoveRange (Size.Height, lines.Count - Size.Height);
  323. }
  324. }
  325. NeedsFormat = false;
  326. }
  327. return lines;
  328. }
  329. }
  330. /// <summary>
  331. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect)"/> is called.
  332. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  333. /// </summary>
  334. /// <remarks>
  335. /// <para>
  336. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  337. /// </para>
  338. /// </remarks>
  339. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  340. static ustring StripCRLF (ustring str, bool keepNewLine = false)
  341. {
  342. var runes = str.ToRuneList ();
  343. for (int i = 0; i < runes.Count; i++) {
  344. switch (runes [i]) {
  345. case '\n':
  346. if (!keepNewLine) {
  347. runes.RemoveAt (i);
  348. }
  349. break;
  350. case '\r':
  351. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  352. runes.RemoveAt (i);
  353. if (!keepNewLine) {
  354. runes.RemoveAt (i);
  355. }
  356. i++;
  357. } else {
  358. if (!keepNewLine) {
  359. runes.RemoveAt (i);
  360. }
  361. }
  362. break;
  363. }
  364. }
  365. return ustring.Make (runes);
  366. }
  367. static ustring ReplaceCRLFWithSpace (ustring str)
  368. {
  369. var runes = str.ToRuneList ();
  370. for (int i = 0; i < runes.Count; i++) {
  371. switch (runes [i]) {
  372. case '\n':
  373. runes [i] = (Rune)' ';
  374. break;
  375. case '\r':
  376. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  377. runes [i] = (Rune)' ';
  378. runes.RemoveAt (i + 1);
  379. i++;
  380. } else {
  381. runes [i] = (Rune)' ';
  382. }
  383. break;
  384. }
  385. }
  386. return ustring.Make (runes);
  387. }
  388. /// <summary>
  389. /// Adds trailing whitespace or truncates <paramref name="text"/>
  390. /// so that it fits exactly <paramref name="width"/> console units.
  391. /// Note that some unicode characters take 2+ columns
  392. /// </summary>
  393. /// <param name="text"></param>
  394. /// <param name="width"></param>
  395. /// <returns></returns>
  396. public static string ClipOrPad (string text, int width)
  397. {
  398. if (string.IsNullOrEmpty (text))
  399. return text;
  400. // if value is not wide enough
  401. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  402. // pad it out with spaces to the given alignment
  403. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  404. return text + new string (' ', toPad);
  405. }
  406. // value is too wide
  407. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  408. }
  409. /// <summary>
  410. /// Formats the provided text to fit within the width provided using word wrapping.
  411. /// </summary>
  412. /// <param name="text">The text to word wrap</param>
  413. /// <param name="width">The width to contain the text to</param>
  414. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  415. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  416. /// <param name="tabWidth">The tab width.</param>
  417. /// <param name="textDirection">The text direction.</param>
  418. /// <returns>Returns a list of word wrapped lines.</returns>
  419. /// <remarks>
  420. /// <para>
  421. /// This method does not do any justification.
  422. /// </para>
  423. /// <para>
  424. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  425. /// </para>
  426. /// </remarks>
  427. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  428. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  429. {
  430. if (width < 0) {
  431. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  432. }
  433. int start = 0, end;
  434. var lines = new List<ustring> ();
  435. if (ustring.IsNullOrEmpty (text)) {
  436. return lines;
  437. }
  438. var runes = StripCRLF (text).ToRuneList ();
  439. if (!preserveTrailingSpaces) {
  440. if (IsHorizontalDirection (textDirection)) {
  441. while ((end = start + Math.Max (GetMaxLengthForWidth (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
  442. while (runes [end] != ' ' && end > start)
  443. end--;
  444. if (end == start)
  445. end = start + GetMaxLengthForWidth (runes.GetRange (end, runes.Count - end), width);
  446. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  447. start = end;
  448. if (runes [end] == ' ') {
  449. start++;
  450. }
  451. }
  452. } else {
  453. while ((end = start + width) < runes.Count) {
  454. while (runes [end] != ' ' && end > start)
  455. end--;
  456. if (end == start)
  457. end = start + width;
  458. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  459. start = end;
  460. if (runes [end] == ' ') {
  461. start++;
  462. }
  463. }
  464. }
  465. } else {
  466. while ((end = start) < runes.Count) {
  467. end = GetNextWhiteSpace (start, width, out bool incomplete);
  468. if (end == 0 && incomplete) {
  469. start = text.RuneCount;
  470. break;
  471. }
  472. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  473. start = end;
  474. if (incomplete) {
  475. start = text.RuneCount;
  476. break;
  477. }
  478. }
  479. }
  480. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  481. {
  482. var lastFrom = from;
  483. var to = from;
  484. var length = cLength;
  485. incomplete = false;
  486. while (length < cWidth && to < runes.Count) {
  487. var rune = runes [to];
  488. if (IsHorizontalDirection (textDirection)) {
  489. length += Rune.ColumnWidth (rune);
  490. } else {
  491. length++;
  492. }
  493. if (length > cWidth) {
  494. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  495. incomplete = true;
  496. }
  497. return to;
  498. }
  499. if (rune == ' ') {
  500. if (length == cWidth) {
  501. return to + 1;
  502. } else if (length > cWidth) {
  503. return to;
  504. } else {
  505. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  506. }
  507. } else if (rune == '\t') {
  508. length += tabWidth + 1;
  509. if (length == tabWidth && tabWidth > cWidth) {
  510. return to + 1;
  511. } else if (length > cWidth && tabWidth > cWidth) {
  512. return to;
  513. } else {
  514. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  515. }
  516. }
  517. to++;
  518. }
  519. if (cLength > 0 && to < runes.Count && runes [to] != ' ' && runes [to] != '\t') {
  520. return from;
  521. } else if (cLength > 0 && to < runes.Count && (runes [to] == ' ' || runes [to] == '\t')) {
  522. return lastFrom;
  523. } else {
  524. return to;
  525. }
  526. }
  527. if (start < text.RuneCount) {
  528. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  529. }
  530. return lines;
  531. }
  532. /// <summary>
  533. /// Justifies text within a specified width.
  534. /// </summary>
  535. /// <param name="text">The text to justify.</param>
  536. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  537. /// <param name="talign">Alignment.</param>
  538. /// <param name="textDirection">The text direction.</param>
  539. /// <returns>Justified and clipped text.</returns>
  540. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  541. {
  542. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
  543. }
  544. /// <summary>
  545. /// Justifies text within a specified width.
  546. /// </summary>
  547. /// <param name="text">The text to justify.</param>
  548. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  549. /// <param name="justify">Justify.</param>
  550. /// <param name="textDirection">The text direction.</param>
  551. /// <returns>Justified and clipped text.</returns>
  552. public static ustring ClipAndJustify (ustring text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  553. {
  554. if (width < 0) {
  555. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  556. }
  557. if (ustring.IsNullOrEmpty (text)) {
  558. return text;
  559. }
  560. var runes = text.ToRuneList ();
  561. int slen = runes.Count;
  562. if (slen > width) {
  563. if (IsHorizontalDirection (textDirection)) {
  564. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  565. } else {
  566. return ustring.Make (runes.GetRange (0, width));
  567. }
  568. } else {
  569. if (justify) {
  570. return Justify (text, width, ' ', textDirection);
  571. } else if (IsHorizontalDirection (textDirection) && GetTextWidth (text) > width) {
  572. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  573. }
  574. return text;
  575. }
  576. }
  577. /// <summary>
  578. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  579. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  580. /// </summary>
  581. /// <param name="text"></param>
  582. /// <param name="width"></param>
  583. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  584. /// <param name="textDirection">The text direction.</param>
  585. /// <returns>The justified text.</returns>
  586. public static ustring Justify (ustring text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  587. {
  588. if (width < 0) {
  589. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  590. }
  591. if (ustring.IsNullOrEmpty (text)) {
  592. return text;
  593. }
  594. var words = text.Split (ustring.Make (' '));
  595. int textCount;
  596. if (IsHorizontalDirection (textDirection)) {
  597. textCount = words.Sum (arg => GetTextWidth (arg));
  598. } else {
  599. textCount = words.Sum (arg => arg.RuneCount);
  600. }
  601. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  602. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  603. var s = new System.Text.StringBuilder ();
  604. for (int w = 0; w < words.Length; w++) {
  605. var x = words [w];
  606. s.Append (x);
  607. if (w + 1 < words.Length)
  608. for (int i = 0; i < spaces; i++)
  609. s.Append (spaceChar);
  610. if (extras > 0) {
  611. extras--;
  612. }
  613. }
  614. return ustring.Make (s.ToString ());
  615. }
  616. static char [] whitespace = new char [] { ' ', '\t' };
  617. private int hotKeyPos;
  618. /// <summary>
  619. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  620. /// </summary>
  621. /// <param name="text"></param>
  622. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  623. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  624. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  625. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  626. /// <param name="tabWidth">The tab width.</param>
  627. /// <param name="textDirection">The text direction.</param>
  628. /// <returns>A list of word wrapped lines.</returns>
  629. /// <remarks>
  630. /// <para>
  631. /// An empty <c>text</c> string will result in one empty line.
  632. /// </para>
  633. /// <para>
  634. /// If <c>width</c> is 0, a single, empty line will be returned.
  635. /// </para>
  636. /// <para>
  637. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  638. /// </para>
  639. /// </remarks>
  640. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  641. {
  642. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  643. }
  644. /// <summary>
  645. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  646. /// </summary>
  647. /// <param name="text"></param>
  648. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  649. /// <param name="justify">Specifies whether the text should be justified.</param>
  650. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  651. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  652. /// <param name="tabWidth">The tab width.</param>
  653. /// <param name="textDirection">The text direction.</param>
  654. /// <returns>A list of word wrapped lines.</returns>
  655. /// <remarks>
  656. /// <para>
  657. /// An empty <c>text</c> string will result in one empty line.
  658. /// </para>
  659. /// <para>
  660. /// If <c>width</c> is 0, a single, empty line will be returned.
  661. /// </para>
  662. /// <para>
  663. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  664. /// </para>
  665. /// </remarks>
  666. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  667. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  668. {
  669. if (width < 0) {
  670. throw new ArgumentOutOfRangeException ("width cannot be negative");
  671. }
  672. List<ustring> lineResult = new List<ustring> ();
  673. if (ustring.IsNullOrEmpty (text) || width == 0) {
  674. lineResult.Add (ustring.Empty);
  675. return lineResult;
  676. }
  677. if (wordWrap == false) {
  678. text = ReplaceCRLFWithSpace (text);
  679. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  680. return lineResult;
  681. }
  682. var runes = StripCRLF (text, true).ToRuneList ();
  683. int runeCount = runes.Count;
  684. int lp = 0;
  685. for (int i = 0; i < runeCount; i++) {
  686. Rune c = runes [i];
  687. if (c == '\n') {
  688. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  689. foreach (var line in wrappedLines) {
  690. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  691. }
  692. if (wrappedLines.Count == 0) {
  693. lineResult.Add (ustring.Empty);
  694. }
  695. lp = i + 1;
  696. }
  697. }
  698. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  699. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  700. }
  701. return lineResult;
  702. }
  703. /// <summary>
  704. /// Computes the number of lines needed to render the specified text given the width.
  705. /// </summary>
  706. /// <returns>Number of lines.</returns>
  707. /// <param name="text">Text, may contain newlines.</param>
  708. /// <param name="width">The minimum width for the text.</param>
  709. public static int MaxLines (ustring text, int width)
  710. {
  711. var result = TextFormatter.Format (text, width, false, true);
  712. return result.Count;
  713. }
  714. /// <summary>
  715. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  716. /// </summary>
  717. /// <returns>Max width of lines.</returns>
  718. /// <param name="text">Text, may contain newlines.</param>
  719. /// <param name="width">The minimum width for the text.</param>
  720. public static int MaxWidth (ustring text, int width)
  721. {
  722. var result = TextFormatter.Format (text, width, false, true);
  723. var max = 0;
  724. result.ForEach (s => {
  725. var m = 0;
  726. s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
  727. if (m > max) {
  728. max = m;
  729. }
  730. });
  731. return max;
  732. }
  733. /// <summary>
  734. /// Gets the total width of the passed text.
  735. /// </summary>
  736. /// <param name="text"></param>
  737. /// <returns>The text width.</returns>
  738. public static int GetTextWidth (ustring text)
  739. {
  740. return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
  741. }
  742. /// <summary>
  743. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  744. /// and the <paramref name="length"/>.
  745. /// </summary>
  746. /// <param name="lines">The lines.</param>
  747. /// <param name="startIndex">The start index.</param>
  748. /// <param name="length">The length.</param>
  749. /// <returns>The maximum characters width.</returns>
  750. public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
  751. {
  752. var max = 0;
  753. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  754. var runes = lines [i];
  755. if (runes.Length > 0)
  756. max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
  757. }
  758. return max;
  759. }
  760. /// <summary>
  761. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  762. /// and the <paramref name="length"/>.
  763. /// </summary>
  764. /// <param name="text">The text.</param>
  765. /// <param name="startIndex">The start index.</param>
  766. /// <param name="length">The length.</param>
  767. /// <returns>The maximum characters width.</returns>
  768. public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
  769. {
  770. var max = 0;
  771. var runes = text.ToRunes ();
  772. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  773. max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
  774. }
  775. return max;
  776. }
  777. /// <summary>
  778. /// Gets the index position from the text based on the <paramref name="width"/>.
  779. /// </summary>
  780. /// <param name="text">The text.</param>
  781. /// <param name="width">The width.</param>
  782. /// <returns>The index of the text that fit the width.</returns>
  783. public static int GetMaxLengthForWidth (ustring text, int width)
  784. {
  785. var runes = text.ToRuneList ();
  786. var runesLength = 0;
  787. var runeIdx = 0;
  788. for (; runeIdx < runes.Count; runeIdx++) {
  789. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  790. if (runesLength + runeWidth > width) {
  791. break;
  792. }
  793. runesLength += runeWidth;
  794. }
  795. return runeIdx;
  796. }
  797. /// <summary>
  798. /// Gets the index position from the list based on the <paramref name="width"/>.
  799. /// </summary>
  800. /// <param name="runes">The runes.</param>
  801. /// <param name="width">The width.</param>
  802. /// <returns>The index of the list that fit the width.</returns>
  803. public static int GetMaxLengthForWidth (List<Rune> runes, int width)
  804. {
  805. var runesLength = 0;
  806. var runeIdx = 0;
  807. for (; runeIdx < runes.Count; runeIdx++) {
  808. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  809. if (runesLength + runeWidth > width) {
  810. break;
  811. }
  812. runesLength += runeWidth;
  813. }
  814. return runeIdx;
  815. }
  816. /// <summary>
  817. /// Gets the index position from the list based on the <paramref name="width"/>.
  818. /// </summary>
  819. /// <param name="lines">The lines.</param>
  820. /// <param name="width">The width.</param>
  821. /// <returns>The index of the list that fit the width.</returns>
  822. public static int GetMaxColsForWidth (List<ustring> lines, int width)
  823. {
  824. var runesLength = 0;
  825. var lineIdx = 0;
  826. for (; lineIdx < lines.Count; lineIdx++) {
  827. var runes = lines [lineIdx].ToRuneList ();
  828. var maxRruneWidth = runes.Count > 0
  829. ? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
  830. if (runesLength + maxRruneWidth > width) {
  831. break;
  832. }
  833. runesLength += maxRruneWidth;
  834. }
  835. return lineIdx;
  836. }
  837. /// <summary>
  838. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  839. /// </summary>
  840. /// <param name="x">The x location of the rectangle</param>
  841. /// <param name="y">The y location of the rectangle</param>
  842. /// <param name="text">The text to measure</param>
  843. /// <param name="direction">The text direction.</param>
  844. /// <returns></returns>
  845. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  846. {
  847. if (ustring.IsNullOrEmpty (text)) {
  848. return new Rect (new Point (x, y), Size.Empty);
  849. }
  850. int w, h;
  851. if (IsHorizontalDirection (direction)) {
  852. int mw = 0;
  853. int ml = 1;
  854. int cols = 0;
  855. foreach (var rune in text) {
  856. if (rune == '\n') {
  857. ml++;
  858. if (cols > mw) {
  859. mw = cols;
  860. }
  861. cols = 0;
  862. } else if (rune != '\r') {
  863. cols++;
  864. var rw = Rune.ColumnWidth (rune);
  865. if (rw > 0) {
  866. rw--;
  867. }
  868. cols += rw;
  869. }
  870. }
  871. if (cols > mw) {
  872. mw = cols;
  873. }
  874. w = mw;
  875. h = ml;
  876. } else {
  877. int vw = 1, cw = 1;
  878. int vh = 0;
  879. int rows = 0;
  880. foreach (var rune in text) {
  881. if (rune == '\n') {
  882. vw++;
  883. if (rows > vh) {
  884. vh = rows;
  885. }
  886. rows = 0;
  887. cw = 1;
  888. } else if (rune != '\r') {
  889. rows++;
  890. var rw = Rune.ColumnWidth (rune);
  891. if (cw < rw) {
  892. cw = rw;
  893. vw++;
  894. }
  895. }
  896. }
  897. if (rows > vh) {
  898. vh = rows;
  899. }
  900. w = vw;
  901. h = vh;
  902. }
  903. return new Rect (x, y, w, h);
  904. }
  905. /// <summary>
  906. /// Finds the hotkey and its location in text.
  907. /// </summary>
  908. /// <param name="text">The text to look in.</param>
  909. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  910. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  911. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  912. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  913. /// <param name="hotKey">Outputs the hotKey.</param>
  914. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  915. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  916. {
  917. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  918. hotPos = -1;
  919. hotKey = Key.Unknown;
  920. return false;
  921. }
  922. Rune hot_key = (Rune)0;
  923. int hot_pos = -1;
  924. // Use first hot_key char passed into 'hotKey'.
  925. // TODO: Ignore hot_key of two are provided
  926. // TODO: Do not support non-alphanumeric chars that can't be typed
  927. int i = 0;
  928. foreach (Rune c in text) {
  929. if ((char)c != 0xFFFD) {
  930. if (c == hotKeySpecifier) {
  931. hot_pos = i;
  932. } else if (hot_pos > -1) {
  933. hot_key = c;
  934. break;
  935. }
  936. }
  937. i++;
  938. }
  939. // Legacy support - use first upper case char if the specifier was not found
  940. if (hot_pos == -1 && firstUpperCase) {
  941. i = 0;
  942. foreach (Rune c in text) {
  943. if ((char)c != 0xFFFD) {
  944. if (Rune.IsUpper (c)) {
  945. hot_key = c;
  946. hot_pos = i;
  947. break;
  948. }
  949. }
  950. i++;
  951. }
  952. }
  953. if (hot_key != (Rune)0 && hot_pos != -1) {
  954. hotPos = hot_pos;
  955. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  956. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  957. return true;
  958. }
  959. }
  960. hotPos = -1;
  961. hotKey = Key.Unknown;
  962. return false;
  963. }
  964. /// <summary>
  965. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  966. /// it as the hotkey.
  967. /// </summary>
  968. /// <param name="text">The text to tag the hotkey in.</param>
  969. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  970. /// <returns>The text with the hotkey tagged.</returns>
  971. /// <remarks>
  972. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  973. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  974. /// </remarks>
  975. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  976. {
  977. // Set the high bit
  978. var runes = text.ToRuneList ();
  979. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  980. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  981. }
  982. return ustring.Make (runes);
  983. }
  984. /// <summary>
  985. /// Removes the hotkey specifier from text.
  986. /// </summary>
  987. /// <param name="text">The text to manipulate.</param>
  988. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  989. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  990. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  991. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  992. {
  993. if (ustring.IsNullOrEmpty (text)) {
  994. return text;
  995. }
  996. // Scan
  997. ustring start = ustring.Empty;
  998. int i = 0;
  999. foreach (Rune c in text) {
  1000. if (c == hotKeySpecifier && i == hotPos) {
  1001. i++;
  1002. continue;
  1003. }
  1004. start += ustring.Make (c);
  1005. i++;
  1006. }
  1007. return start;
  1008. }
  1009. /// <summary>
  1010. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  1011. /// </summary>
  1012. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1013. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1014. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1015. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1016. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default)
  1017. {
  1018. // With this check, we protect against subclasses with overrides of Text (like Button)
  1019. if (ustring.IsNullOrEmpty (text)) {
  1020. return;
  1021. }
  1022. Application.Driver?.SetAttribute (normalColor);
  1023. // Use "Lines" to ensure a Format (don't use "lines"))
  1024. var linesFormated = Lines;
  1025. switch (textDirection) {
  1026. case TextDirection.TopBottom_RightLeft:
  1027. case TextDirection.LeftRight_BottomTop:
  1028. case TextDirection.RightLeft_BottomTop:
  1029. case TextDirection.BottomTop_RightLeft:
  1030. linesFormated.Reverse ();
  1031. break;
  1032. }
  1033. var isVertical = IsVerticalDirection (textDirection);
  1034. for (int line = 0; line < linesFormated.Count; line++) {
  1035. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1036. continue;
  1037. var runes = lines [line].ToRunes ();
  1038. switch (textDirection) {
  1039. case TextDirection.RightLeft_BottomTop:
  1040. case TextDirection.RightLeft_TopBottom:
  1041. case TextDirection.BottomTop_LeftRight:
  1042. case TextDirection.BottomTop_RightLeft:
  1043. runes = runes.Reverse ().ToArray ();
  1044. break;
  1045. }
  1046. // When text is justified, we lost left or right, so we use the direction to align.
  1047. int x, y;
  1048. // Horizontal Alignment
  1049. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  1050. if (isVertical) {
  1051. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1052. x = bounds.Right - runesWidth;
  1053. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1054. } else {
  1055. var runesWidth = GetTextWidth (ustring.Make (runes));
  1056. x = bounds.Right - runesWidth;
  1057. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1058. }
  1059. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  1060. if (isVertical) {
  1061. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line) : 0;
  1062. x = bounds.Left + runesWidth;
  1063. } else {
  1064. x = bounds.Left;
  1065. }
  1066. CursorPosition = hotKeyPos;
  1067. } else if (textAlignment == TextAlignment.Centered) {
  1068. if (isVertical) {
  1069. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1070. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1071. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1072. } else {
  1073. var runesWidth = GetTextWidth (ustring.Make (runes));
  1074. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1075. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1076. }
  1077. } else {
  1078. throw new ArgumentOutOfRangeException ();
  1079. }
  1080. // Vertical Alignment
  1081. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  1082. if (isVertical) {
  1083. y = bounds.Bottom - runes.Length;
  1084. } else {
  1085. y = bounds.Bottom - Lines.Count + line;
  1086. }
  1087. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  1088. if (isVertical) {
  1089. y = bounds.Top;
  1090. } else {
  1091. y = bounds.Top + line;
  1092. }
  1093. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  1094. if (isVertical) {
  1095. var s = (bounds.Height - runes.Length) / 2;
  1096. y = bounds.Top + s;
  1097. } else {
  1098. var s = (bounds.Height - Lines.Count) / 2;
  1099. y = bounds.Top + line + s;
  1100. }
  1101. } else {
  1102. throw new ArgumentOutOfRangeException ();
  1103. }
  1104. var start = isVertical ? bounds.Top : bounds.Left;
  1105. var size = isVertical ? bounds.Height : bounds.Width;
  1106. var current = start;
  1107. var savedClip = Application.Driver?.Clip;
  1108. if (Application.Driver != null && containerBounds != default) {
  1109. Application.Driver.Clip = containerBounds == default
  1110. ? bounds
  1111. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1112. Math.Max (containerBounds.Y, bounds.Y),
  1113. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1114. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1115. }
  1116. for (var idx = (isVertical ? start - y : start - x); current < start + size; idx++) {
  1117. if (idx < 0) {
  1118. current++;
  1119. continue;
  1120. } else if (idx > runes.Length - 1) {
  1121. break;
  1122. }
  1123. var rune = (Rune)' ';
  1124. if (isVertical) {
  1125. Application.Driver?.Move (x, current);
  1126. if (idx >= 0 && idx < runes.Length) {
  1127. rune = runes [idx];
  1128. }
  1129. } else {
  1130. Application.Driver?.Move (current, y);
  1131. if (idx >= 0 && idx < runes.Length) {
  1132. rune = runes [idx];
  1133. }
  1134. }
  1135. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  1136. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1137. (!isVertical && textAlignment == TextAlignment.Justified)) {
  1138. CursorPosition = idx - start;
  1139. }
  1140. Application.Driver?.SetAttribute (hotColor);
  1141. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  1142. Application.Driver?.SetAttribute (normalColor);
  1143. } else {
  1144. Application.Driver?.AddRune (rune);
  1145. }
  1146. var runeWidth = Math.Max (Rune.ColumnWidth (rune), 1);
  1147. if (isVertical) {
  1148. current++;
  1149. } else {
  1150. current += runeWidth;
  1151. }
  1152. if (!isVertical && idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > start + size) {
  1153. break;
  1154. }
  1155. }
  1156. if (Application.Driver != null)
  1157. Application.Driver.Clip = (Rect)savedClip;
  1158. }
  1159. }
  1160. }
  1161. }