TextFormatter.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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)
  341. {
  342. var runes = str.ToRuneList ();
  343. for (int i = 0; i < runes.Count; i++) {
  344. switch (runes [i]) {
  345. case '\n':
  346. runes.RemoveAt (i);
  347. break;
  348. case '\r':
  349. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  350. runes.RemoveAt (i);
  351. runes.RemoveAt (i + 1);
  352. i++;
  353. } else {
  354. runes.RemoveAt (i);
  355. }
  356. break;
  357. }
  358. }
  359. return ustring.Make (runes);
  360. }
  361. static ustring ReplaceCRLFWithSpace (ustring str)
  362. {
  363. var runes = str.ToRuneList ();
  364. for (int i = 0; i < runes.Count; i++) {
  365. switch (runes [i]) {
  366. case '\n':
  367. runes [i] = (Rune)' ';
  368. break;
  369. case '\r':
  370. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  371. runes [i] = (Rune)' ';
  372. runes.RemoveAt (i + 1);
  373. i++;
  374. } else {
  375. runes [i] = (Rune)' ';
  376. }
  377. break;
  378. }
  379. }
  380. return ustring.Make (runes);
  381. }
  382. /// <summary>
  383. /// Adds trailing whitespace or truncates <paramref name="text"/>
  384. /// so that it fits exactly <paramref name="width"/> console units.
  385. /// Note that some unicode characters take 2+ columns
  386. /// </summary>
  387. /// <param name="text"></param>
  388. /// <param name="width"></param>
  389. /// <returns></returns>
  390. public static string ClipOrPad (string text, int width)
  391. {
  392. if (string.IsNullOrEmpty (text))
  393. return text;
  394. // if value is not wide enough
  395. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  396. // pad it out with spaces to the given alignment
  397. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  398. return text + new string (' ', toPad);
  399. }
  400. // value is too wide
  401. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  402. }
  403. /// <summary>
  404. /// Formats the provided text to fit within the width provided using word wrapping.
  405. /// </summary>
  406. /// <param name="text">The text to word wrap</param>
  407. /// <param name="width">The width to contain the text to</param>
  408. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  409. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  410. /// <param name="tabWidth">The tab width.</param>
  411. /// <param name="textDirection">The text direction.</param>
  412. /// <returns>Returns a list of word wrapped lines.</returns>
  413. /// <remarks>
  414. /// <para>
  415. /// This method does not do any justification.
  416. /// </para>
  417. /// <para>
  418. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  419. /// </para>
  420. /// </remarks>
  421. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  422. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  423. {
  424. if (width < 0) {
  425. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  426. }
  427. int start = 0, end;
  428. var lines = new List<ustring> ();
  429. if (ustring.IsNullOrEmpty (text)) {
  430. return lines;
  431. }
  432. var runes = StripCRLF (text).ToRuneList ();
  433. if (!preserveTrailingSpaces) {
  434. if (IsHorizontalDirection (textDirection)) {
  435. while ((end = start + Math.Max (GetMaxLengthForWidth (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
  436. while (runes [end] != ' ' && end > start)
  437. end--;
  438. if (end == start)
  439. end = start + GetMaxLengthForWidth (runes.GetRange (end, runes.Count - end), width);
  440. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  441. start = end;
  442. if (runes [end] == ' ') {
  443. start++;
  444. }
  445. }
  446. } else {
  447. while ((end = start + width) < runes.Count) {
  448. while (runes [end] != ' ' && end > start)
  449. end--;
  450. if (end == start)
  451. end = start + width;
  452. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  453. start = end;
  454. if (runes [end] == ' ') {
  455. start++;
  456. }
  457. }
  458. }
  459. } else {
  460. while ((end = start) < runes.Count) {
  461. end = GetNextWhiteSpace (start, width, out bool incomplete);
  462. if (end == 0 && incomplete) {
  463. start = text.RuneCount;
  464. break;
  465. }
  466. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  467. start = end;
  468. if (incomplete) {
  469. start = text.RuneCount;
  470. break;
  471. }
  472. }
  473. }
  474. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  475. {
  476. var to = from;
  477. var length = cLength;
  478. incomplete = false;
  479. while (length < cWidth && to < runes.Count) {
  480. var rune = runes [to];
  481. if (IsHorizontalDirection (textDirection)) {
  482. length += Rune.ColumnWidth (rune);
  483. } else {
  484. length++;
  485. }
  486. if (length > cWidth) {
  487. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  488. incomplete = true;
  489. }
  490. return to;
  491. }
  492. if (rune == ' ') {
  493. if (length == cWidth) {
  494. return to + 1;
  495. } else if (length > cWidth) {
  496. return to;
  497. } else {
  498. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  499. }
  500. } else if (rune == '\t') {
  501. length += tabWidth + 1;
  502. if (length == tabWidth && tabWidth > cWidth) {
  503. return to + 1;
  504. } else if (length > cWidth && tabWidth > cWidth) {
  505. return to;
  506. } else {
  507. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  508. }
  509. }
  510. to++;
  511. }
  512. if (cLength > 0 && to < runes.Count && runes [to] != ' ') {
  513. return from;
  514. } else {
  515. return to;
  516. }
  517. }
  518. if (start < text.RuneCount) {
  519. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  520. }
  521. return lines;
  522. }
  523. /// <summary>
  524. /// Justifies text within a specified width.
  525. /// </summary>
  526. /// <param name="text">The text to justify.</param>
  527. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  528. /// <param name="talign">Alignment.</param>
  529. /// <param name="textDirection">The text direction.</param>
  530. /// <returns>Justified and clipped text.</returns>
  531. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  532. {
  533. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
  534. }
  535. /// <summary>
  536. /// Justifies text within a specified width.
  537. /// </summary>
  538. /// <param name="text">The text to justify.</param>
  539. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  540. /// <param name="justify">Justify.</param>
  541. /// <param name="textDirection">The text direction.</param>
  542. /// <returns>Justified and clipped text.</returns>
  543. public static ustring ClipAndJustify (ustring text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  544. {
  545. if (width < 0) {
  546. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  547. }
  548. if (ustring.IsNullOrEmpty (text)) {
  549. return text;
  550. }
  551. var runes = text.ToRuneList ();
  552. int slen = runes.Count;
  553. if (slen > width) {
  554. if (IsHorizontalDirection (textDirection)) {
  555. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  556. } else {
  557. return ustring.Make (runes.GetRange (0, width));
  558. }
  559. } else {
  560. if (justify) {
  561. return Justify (text, width, ' ', textDirection);
  562. } else if (IsHorizontalDirection (textDirection) && GetTextWidth (text) > width) {
  563. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  564. }
  565. return text;
  566. }
  567. }
  568. /// <summary>
  569. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  570. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  571. /// </summary>
  572. /// <param name="text"></param>
  573. /// <param name="width"></param>
  574. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  575. /// <param name="textDirection">The text direction.</param>
  576. /// <returns>The justified text.</returns>
  577. public static ustring Justify (ustring text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  578. {
  579. if (width < 0) {
  580. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  581. }
  582. if (ustring.IsNullOrEmpty (text)) {
  583. return text;
  584. }
  585. var words = text.Split (ustring.Make (' '));
  586. int textCount;
  587. if (IsHorizontalDirection (textDirection)) {
  588. textCount = words.Sum (arg => GetTextWidth (arg));
  589. } else {
  590. textCount = words.Sum (arg => arg.RuneCount);
  591. }
  592. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  593. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  594. var s = new System.Text.StringBuilder ();
  595. for (int w = 0; w < words.Length; w++) {
  596. var x = words [w];
  597. s.Append (x);
  598. if (w + 1 < words.Length)
  599. for (int i = 0; i < spaces; i++)
  600. s.Append (spaceChar);
  601. if (extras > 0) {
  602. extras--;
  603. }
  604. }
  605. return ustring.Make (s.ToString ());
  606. }
  607. static char [] whitespace = new char [] { ' ', '\t' };
  608. private int hotKeyPos;
  609. /// <summary>
  610. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  611. /// </summary>
  612. /// <param name="text"></param>
  613. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  614. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  615. /// <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>
  616. /// <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>
  617. /// <param name="tabWidth">The tab width.</param>
  618. /// <param name="textDirection">The text direction.</param>
  619. /// <returns>A list of word wrapped lines.</returns>
  620. /// <remarks>
  621. /// <para>
  622. /// An empty <c>text</c> string will result in one empty line.
  623. /// </para>
  624. /// <para>
  625. /// If <c>width</c> is 0, a single, empty line will be returned.
  626. /// </para>
  627. /// <para>
  628. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  629. /// </para>
  630. /// </remarks>
  631. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  632. {
  633. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  634. }
  635. /// <summary>
  636. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  637. /// </summary>
  638. /// <param name="text"></param>
  639. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  640. /// <param name="justify">Specifies whether the text should be justified.</param>
  641. /// <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>
  642. /// <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>
  643. /// <param name="tabWidth">The tab width.</param>
  644. /// <param name="textDirection">The text direction.</param>
  645. /// <returns>A list of word wrapped lines.</returns>
  646. /// <remarks>
  647. /// <para>
  648. /// An empty <c>text</c> string will result in one empty line.
  649. /// </para>
  650. /// <para>
  651. /// If <c>width</c> is 0, a single, empty line will be returned.
  652. /// </para>
  653. /// <para>
  654. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  655. /// </para>
  656. /// </remarks>
  657. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  658. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  659. {
  660. if (width < 0) {
  661. throw new ArgumentOutOfRangeException ("width cannot be negative");
  662. }
  663. List<ustring> lineResult = new List<ustring> ();
  664. if (ustring.IsNullOrEmpty (text) || width == 0) {
  665. lineResult.Add (ustring.Empty);
  666. return lineResult;
  667. }
  668. if (wordWrap == false) {
  669. text = ReplaceCRLFWithSpace (text);
  670. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  671. return lineResult;
  672. }
  673. var runes = text.ToRuneList ();
  674. int runeCount = runes.Count;
  675. int lp = 0;
  676. for (int i = 0; i < runeCount; i++) {
  677. Rune c = runes [i];
  678. if (c == '\n') {
  679. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  680. foreach (var line in wrappedLines) {
  681. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  682. }
  683. if (wrappedLines.Count == 0) {
  684. lineResult.Add (ustring.Empty);
  685. }
  686. lp = i + 1;
  687. }
  688. }
  689. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  690. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  691. }
  692. return lineResult;
  693. }
  694. /// <summary>
  695. /// Computes the number of lines needed to render the specified text given the width.
  696. /// </summary>
  697. /// <returns>Number of lines.</returns>
  698. /// <param name="text">Text, may contain newlines.</param>
  699. /// <param name="width">The minimum width for the text.</param>
  700. public static int MaxLines (ustring text, int width)
  701. {
  702. var result = TextFormatter.Format (text, width, false, true);
  703. return result.Count;
  704. }
  705. /// <summary>
  706. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  707. /// </summary>
  708. /// <returns>Max width of lines.</returns>
  709. /// <param name="text">Text, may contain newlines.</param>
  710. /// <param name="width">The minimum width for the text.</param>
  711. public static int MaxWidth (ustring text, int width)
  712. {
  713. var result = TextFormatter.Format (text, width, false, true);
  714. var max = 0;
  715. result.ForEach (s => {
  716. var m = 0;
  717. s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
  718. if (m > max) {
  719. max = m;
  720. }
  721. });
  722. return max;
  723. }
  724. /// <summary>
  725. /// Gets the total width of the passed text.
  726. /// </summary>
  727. /// <param name="text"></param>
  728. /// <returns>The text width.</returns>
  729. public static int GetTextWidth (ustring text)
  730. {
  731. return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
  732. }
  733. /// <summary>
  734. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  735. /// and the <paramref name="length"/>.
  736. /// </summary>
  737. /// <param name="lines">The lines.</param>
  738. /// <param name="startIndex">The start index.</param>
  739. /// <param name="length">The length.</param>
  740. /// <returns>The maximum characters width.</returns>
  741. public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
  742. {
  743. var max = 0;
  744. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  745. var runes = lines [i];
  746. if (runes.Length > 0)
  747. max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
  748. }
  749. return max;
  750. }
  751. /// <summary>
  752. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  753. /// and the <paramref name="length"/>.
  754. /// </summary>
  755. /// <param name="text">The text.</param>
  756. /// <param name="startIndex">The start index.</param>
  757. /// <param name="length">The length.</param>
  758. /// <returns>The maximum characters width.</returns>
  759. public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
  760. {
  761. var max = 0;
  762. var runes = text.ToRunes ();
  763. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  764. max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
  765. }
  766. return max;
  767. }
  768. /// <summary>
  769. /// Gets the index position from the text based on the <paramref name="width"/>.
  770. /// </summary>
  771. /// <param name="text">The text.</param>
  772. /// <param name="width">The width.</param>
  773. /// <returns>The index of the text that fit the width.</returns>
  774. public static int GetMaxLengthForWidth (ustring text, int width)
  775. {
  776. var runes = text.ToRuneList ();
  777. var runesLength = 0;
  778. var runeIdx = 0;
  779. for (; runeIdx < runes.Count; runeIdx++) {
  780. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  781. if (runesLength + runeWidth > width) {
  782. break;
  783. }
  784. runesLength += runeWidth;
  785. }
  786. return runeIdx;
  787. }
  788. /// <summary>
  789. /// Gets the index position from the list based on the <paramref name="width"/>.
  790. /// </summary>
  791. /// <param name="runes">The runes.</param>
  792. /// <param name="width">The width.</param>
  793. /// <returns>The index of the list that fit the width.</returns>
  794. public static int GetMaxLengthForWidth (List<Rune> runes, int width)
  795. {
  796. var runesLength = 0;
  797. var runeIdx = 0;
  798. for (; runeIdx < runes.Count; runeIdx++) {
  799. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  800. if (runesLength + runeWidth > width) {
  801. break;
  802. }
  803. runesLength += runeWidth;
  804. }
  805. return runeIdx;
  806. }
  807. /// <summary>
  808. /// Gets the index position from the list based on the <paramref name="width"/>.
  809. /// </summary>
  810. /// <param name="lines">The lines.</param>
  811. /// <param name="width">The width.</param>
  812. /// <returns>The index of the list that fit the width.</returns>
  813. public static int GetMaxColsForWidth (List<ustring> lines, int width)
  814. {
  815. var runesLength = 0;
  816. var lineIdx = 0;
  817. for (; lineIdx < lines.Count; lineIdx++) {
  818. var runes = lines [lineIdx].ToRuneList ();
  819. var maxRruneWidth = runes.Count > 0
  820. ? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
  821. if (runesLength + maxRruneWidth > width) {
  822. break;
  823. }
  824. runesLength += maxRruneWidth;
  825. }
  826. return lineIdx;
  827. }
  828. /// <summary>
  829. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  830. /// </summary>
  831. /// <param name="x">The x location of the rectangle</param>
  832. /// <param name="y">The y location of the rectangle</param>
  833. /// <param name="text">The text to measure</param>
  834. /// <param name="direction">The text direction.</param>
  835. /// <returns></returns>
  836. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  837. {
  838. if (ustring.IsNullOrEmpty (text)) {
  839. return new Rect (new Point (x, y), Size.Empty);
  840. }
  841. int w, h;
  842. if (IsHorizontalDirection (direction)) {
  843. int mw = 0;
  844. int ml = 1;
  845. int cols = 0;
  846. foreach (var rune in text) {
  847. if (rune == '\n') {
  848. ml++;
  849. if (cols > mw) {
  850. mw = cols;
  851. }
  852. cols = 0;
  853. } else if (rune != '\r') {
  854. cols++;
  855. var rw = Rune.ColumnWidth (rune);
  856. if (rw > 0) {
  857. rw--;
  858. }
  859. cols += rw;
  860. }
  861. }
  862. if (cols > mw) {
  863. mw = cols;
  864. }
  865. w = mw;
  866. h = ml;
  867. } else {
  868. int vw = 1, cw = 1;
  869. int vh = 0;
  870. int rows = 0;
  871. foreach (var rune in text) {
  872. if (rune == '\n') {
  873. vw++;
  874. if (rows > vh) {
  875. vh = rows;
  876. }
  877. rows = 0;
  878. cw = 1;
  879. } else if (rune != '\r') {
  880. rows++;
  881. var rw = Rune.ColumnWidth (rune);
  882. if (cw < rw) {
  883. cw = rw;
  884. vw++;
  885. }
  886. }
  887. }
  888. if (rows > vh) {
  889. vh = rows;
  890. }
  891. w = vw;
  892. h = vh;
  893. }
  894. return new Rect (x, y, w, h);
  895. }
  896. /// <summary>
  897. /// Finds the hotkey and its location in text.
  898. /// </summary>
  899. /// <param name="text">The text to look in.</param>
  900. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  901. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  902. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  903. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  904. /// <param name="hotKey">Outputs the hotKey.</param>
  905. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  906. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  907. {
  908. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  909. hotPos = -1;
  910. hotKey = Key.Unknown;
  911. return false;
  912. }
  913. Rune hot_key = (Rune)0;
  914. int hot_pos = -1;
  915. // Use first hot_key char passed into 'hotKey'.
  916. // TODO: Ignore hot_key of two are provided
  917. // TODO: Do not support non-alphanumeric chars that can't be typed
  918. int i = 0;
  919. foreach (Rune c in text) {
  920. if ((char)c != 0xFFFD) {
  921. if (c == hotKeySpecifier) {
  922. hot_pos = i;
  923. } else if (hot_pos > -1) {
  924. hot_key = c;
  925. break;
  926. }
  927. }
  928. i++;
  929. }
  930. // Legacy support - use first upper case char if the specifier was not found
  931. if (hot_pos == -1 && firstUpperCase) {
  932. i = 0;
  933. foreach (Rune c in text) {
  934. if ((char)c != 0xFFFD) {
  935. if (Rune.IsUpper (c)) {
  936. hot_key = c;
  937. hot_pos = i;
  938. break;
  939. }
  940. }
  941. i++;
  942. }
  943. }
  944. if (hot_key != (Rune)0 && hot_pos != -1) {
  945. hotPos = hot_pos;
  946. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  947. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  948. return true;
  949. }
  950. }
  951. hotPos = -1;
  952. hotKey = Key.Unknown;
  953. return false;
  954. }
  955. /// <summary>
  956. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  957. /// it as the hotkey.
  958. /// </summary>
  959. /// <param name="text">The text to tag the hotkey in.</param>
  960. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  961. /// <returns>The text with the hotkey tagged.</returns>
  962. /// <remarks>
  963. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  964. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  965. /// </remarks>
  966. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  967. {
  968. // Set the high bit
  969. var runes = text.ToRuneList ();
  970. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  971. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  972. }
  973. return ustring.Make (runes);
  974. }
  975. /// <summary>
  976. /// Removes the hotkey specifier from text.
  977. /// </summary>
  978. /// <param name="text">The text to manipulate.</param>
  979. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  980. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  981. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  982. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  983. {
  984. if (ustring.IsNullOrEmpty (text)) {
  985. return text;
  986. }
  987. // Scan
  988. ustring start = ustring.Empty;
  989. int i = 0;
  990. foreach (Rune c in text) {
  991. if (c == hotKeySpecifier && i == hotPos) {
  992. i++;
  993. continue;
  994. }
  995. start += ustring.Make (c);
  996. i++;
  997. }
  998. return start;
  999. }
  1000. /// <summary>
  1001. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  1002. /// </summary>
  1003. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1004. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1005. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1006. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1007. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default)
  1008. {
  1009. // With this check, we protect against subclasses with overrides of Text (like Button)
  1010. if (ustring.IsNullOrEmpty (text)) {
  1011. return;
  1012. }
  1013. Application.Driver?.SetAttribute (normalColor);
  1014. // Use "Lines" to ensure a Format (don't use "lines"))
  1015. var linesFormated = Lines;
  1016. switch (textDirection) {
  1017. case TextDirection.TopBottom_RightLeft:
  1018. case TextDirection.LeftRight_BottomTop:
  1019. case TextDirection.RightLeft_BottomTop:
  1020. case TextDirection.BottomTop_RightLeft:
  1021. linesFormated.Reverse ();
  1022. break;
  1023. }
  1024. var isVertical = IsVerticalDirection (textDirection);
  1025. for (int line = 0; line < linesFormated.Count; line++) {
  1026. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1027. continue;
  1028. var runes = lines [line].ToRunes ();
  1029. switch (textDirection) {
  1030. case TextDirection.RightLeft_BottomTop:
  1031. case TextDirection.RightLeft_TopBottom:
  1032. case TextDirection.BottomTop_LeftRight:
  1033. case TextDirection.BottomTop_RightLeft:
  1034. runes = runes.Reverse ().ToArray ();
  1035. break;
  1036. }
  1037. // When text is justified, we lost left or right, so we use the direction to align.
  1038. int x, y;
  1039. // Horizontal Alignment
  1040. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  1041. if (isVertical) {
  1042. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1043. x = bounds.Right - runesWidth;
  1044. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1045. } else {
  1046. var runesWidth = GetTextWidth (ustring.Make (runes));
  1047. x = bounds.Right - runesWidth;
  1048. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1049. }
  1050. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  1051. if (isVertical) {
  1052. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line) : 0;
  1053. x = bounds.Left + runesWidth;
  1054. } else {
  1055. x = bounds.Left;
  1056. }
  1057. CursorPosition = hotKeyPos;
  1058. } else if (textAlignment == TextAlignment.Centered) {
  1059. if (isVertical) {
  1060. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1061. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1062. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1063. } else {
  1064. var runesWidth = GetTextWidth (ustring.Make (runes));
  1065. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1066. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1067. }
  1068. } else {
  1069. throw new ArgumentOutOfRangeException ();
  1070. }
  1071. // Vertical Alignment
  1072. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  1073. if (isVertical) {
  1074. y = bounds.Bottom - runes.Length;
  1075. } else {
  1076. y = bounds.Bottom - Lines.Count + line;
  1077. }
  1078. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  1079. if (isVertical) {
  1080. y = bounds.Top;
  1081. } else {
  1082. y = bounds.Top + line;
  1083. }
  1084. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  1085. if (isVertical) {
  1086. var s = (bounds.Height - runes.Length) / 2;
  1087. y = bounds.Top + s;
  1088. } else {
  1089. var s = (bounds.Height - Lines.Count) / 2;
  1090. y = bounds.Top + line + s;
  1091. }
  1092. } else {
  1093. throw new ArgumentOutOfRangeException ();
  1094. }
  1095. var start = isVertical ? bounds.Top : bounds.Left;
  1096. var size = isVertical ? bounds.Height : bounds.Width;
  1097. var current = start;
  1098. var savedClip = Application.Driver?.Clip;
  1099. if (Application.Driver != null && containerBounds != default) {
  1100. Application.Driver.Clip = containerBounds == default
  1101. ? bounds
  1102. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1103. Math.Max (containerBounds.Y, bounds.Y),
  1104. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1105. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1106. }
  1107. for (var idx = (isVertical ? start - y : start - x); current < start + size; idx++) {
  1108. if (idx < 0) {
  1109. current++;
  1110. continue;
  1111. } else if (idx > runes.Length - 1) {
  1112. break;
  1113. }
  1114. var rune = (Rune)' ';
  1115. if (isVertical) {
  1116. Application.Driver?.Move (x, current);
  1117. if (idx >= 0 && idx < runes.Length) {
  1118. rune = runes [idx];
  1119. }
  1120. } else {
  1121. Application.Driver?.Move (current, y);
  1122. if (idx >= 0 && idx < runes.Length) {
  1123. rune = runes [idx];
  1124. }
  1125. }
  1126. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  1127. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1128. (!isVertical && textAlignment == TextAlignment.Justified)) {
  1129. CursorPosition = idx - start;
  1130. }
  1131. Application.Driver?.SetAttribute (hotColor);
  1132. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  1133. Application.Driver?.SetAttribute (normalColor);
  1134. } else {
  1135. Application.Driver?.AddRune (rune);
  1136. }
  1137. var runeWidth = Math.Max (Rune.ColumnWidth (rune), 1);
  1138. if (isVertical) {
  1139. current++;
  1140. } else {
  1141. current += runeWidth;
  1142. }
  1143. if (!isVertical && idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > start + size) {
  1144. break;
  1145. }
  1146. }
  1147. if (Application.Driver != null)
  1148. Application.Driver.Clip = (Rect)savedClip;
  1149. }
  1150. }
  1151. }
  1152. }