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. /// Get or sets a flag if the wrapped text will keep the trailing spaces or
  149. /// the trailing spaces will be trimmed (default).
  150. /// </summary>
  151. public bool PreserveTrailingSpaces { get; set; }
  152. // TODO: Add Vertical Text Alignment
  153. /// <summary>
  154. /// Controls the horizontal text-alignment property.
  155. /// </summary>
  156. /// <value>The text alignment.</value>
  157. public TextAlignment Alignment {
  158. get => textAlignment;
  159. set {
  160. textAlignment = value;
  161. NeedsFormat = true;
  162. }
  163. }
  164. /// <summary>
  165. /// Controls the vertical text-alignment property.
  166. /// </summary>
  167. /// <value>The text vertical alignment.</value>
  168. public VerticalTextAlignment VerticalAlignment {
  169. get => textVerticalAlignment;
  170. set {
  171. textVerticalAlignment = value;
  172. NeedsFormat = true;
  173. }
  174. }
  175. /// <summary>
  176. /// Controls the text-direction property.
  177. /// </summary>
  178. /// <value>The text vertical alignment.</value>
  179. public TextDirection Direction {
  180. get => textDirection;
  181. set {
  182. textDirection = value;
  183. NeedsFormat = true;
  184. }
  185. }
  186. /// <summary>
  187. /// Check if it is a horizontal direction
  188. /// </summary>
  189. public static bool IsHorizontalDirection (TextDirection textDirection)
  190. {
  191. switch (textDirection) {
  192. case TextDirection.LeftRight_TopBottom:
  193. case TextDirection.LeftRight_BottomTop:
  194. case TextDirection.RightLeft_TopBottom:
  195. case TextDirection.RightLeft_BottomTop:
  196. return true;
  197. default:
  198. return false;
  199. }
  200. }
  201. /// <summary>
  202. /// Check if it is a vertical direction
  203. /// </summary>
  204. public static bool IsVerticalDirection (TextDirection textDirection)
  205. {
  206. switch (textDirection) {
  207. case TextDirection.TopBottom_LeftRight:
  208. case TextDirection.TopBottom_RightLeft:
  209. case TextDirection.BottomTop_LeftRight:
  210. case TextDirection.BottomTop_RightLeft:
  211. return true;
  212. default:
  213. return false;
  214. }
  215. }
  216. /// <summary>
  217. /// Check if it is Left to Right direction
  218. /// </summary>
  219. public static bool IsLeftToRight (TextDirection textDirection)
  220. {
  221. switch (textDirection) {
  222. case TextDirection.LeftRight_TopBottom:
  223. case TextDirection.LeftRight_BottomTop:
  224. return true;
  225. default:
  226. return false;
  227. }
  228. }
  229. /// <summary>
  230. /// Check if it is Top to Bottom direction
  231. /// </summary>
  232. public static bool IsTopToBottom (TextDirection textDirection)
  233. {
  234. switch (textDirection) {
  235. case TextDirection.TopBottom_LeftRight:
  236. case TextDirection.TopBottom_RightLeft:
  237. return true;
  238. default:
  239. return false;
  240. }
  241. }
  242. /// <summary>
  243. /// Gets or sets the size of the area the text will be constrained to when formatted.
  244. /// </summary>
  245. public Size Size {
  246. get => size;
  247. set {
  248. size = value;
  249. NeedsFormat = true;
  250. }
  251. }
  252. /// <summary>
  253. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  254. /// </summary>
  255. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  256. /// <summary>
  257. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  258. /// </summary>
  259. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  260. /// <summary>
  261. /// Gets the hotkey. Will be an upper case letter or digit.
  262. /// </summary>
  263. public Key HotKey {
  264. get => hotKey;
  265. internal set {
  266. if (hotKey != value) {
  267. var oldKey = hotKey;
  268. hotKey = value;
  269. HotKeyChanged?.Invoke (oldKey);
  270. }
  271. }
  272. }
  273. /// <summary>
  274. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  275. /// the underlying Rune to be identified as a "private use" Unicode character.
  276. /// </summary>HotKeyTagMask
  277. public uint HotKeyTagMask { get; set; } = 0x100000;
  278. /// <summary>
  279. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  280. /// </summary>
  281. public int CursorPosition { get; set; }
  282. /// <summary>
  283. /// Gets the formatted lines.
  284. /// </summary>
  285. /// <remarks>
  286. /// <para>
  287. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  288. /// <see cref="Format(ustring, int, bool, bool, bool, int, TextDirection)"/> will be called internally.
  289. /// </para>
  290. /// </remarks>
  291. public List<ustring> Lines {
  292. get {
  293. // With this check, we protect against subclasses with overrides of Text
  294. if (ustring.IsNullOrEmpty (Text) || Size.IsEmpty) {
  295. lines = new List<ustring> ();
  296. lines.Add (ustring.Empty);
  297. NeedsFormat = false;
  298. return lines;
  299. }
  300. if (NeedsFormat) {
  301. var shown_text = text;
  302. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out Key newHotKey)) {
  303. HotKey = newHotKey;
  304. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  305. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  306. }
  307. if (IsVerticalDirection (textDirection)) {
  308. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1);
  309. lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth,
  310. PreserveTrailingSpaces, 0, textDirection);
  311. if (!AutoSize) {
  312. colsWidth = GetMaxColsForWidth (lines, Size.Width);
  313. if (lines.Count > colsWidth) {
  314. lines.RemoveRange (colsWidth, lines.Count - colsWidth);
  315. }
  316. }
  317. } else {
  318. lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1,
  319. PreserveTrailingSpaces, 0, textDirection);
  320. if (!AutoSize && lines.Count > Size.Height) {
  321. lines.RemoveRange (Size.Height, lines.Count - Size.Height);
  322. }
  323. }
  324. NeedsFormat = false;
  325. }
  326. return lines;
  327. }
  328. }
  329. /// <summary>
  330. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect)"/> is called.
  331. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  332. /// </summary>
  333. /// <remarks>
  334. /// <para>
  335. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  336. /// </para>
  337. /// </remarks>
  338. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  339. static ustring StripCRLF (ustring str)
  340. {
  341. var runes = str.ToRuneList ();
  342. for (int i = 0; i < runes.Count; i++) {
  343. switch (runes [i]) {
  344. case '\n':
  345. runes.RemoveAt (i);
  346. break;
  347. case '\r':
  348. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  349. runes.RemoveAt (i);
  350. runes.RemoveAt (i + 1);
  351. i++;
  352. } else {
  353. runes.RemoveAt (i);
  354. }
  355. break;
  356. }
  357. }
  358. return ustring.Make (runes);
  359. }
  360. static ustring ReplaceCRLFWithSpace (ustring str)
  361. {
  362. var runes = str.ToRuneList ();
  363. for (int i = 0; i < runes.Count; i++) {
  364. switch (runes [i]) {
  365. case '\n':
  366. runes [i] = (Rune)' ';
  367. break;
  368. case '\r':
  369. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  370. runes [i] = (Rune)' ';
  371. runes.RemoveAt (i + 1);
  372. i++;
  373. } else {
  374. runes [i] = (Rune)' ';
  375. }
  376. break;
  377. }
  378. }
  379. return ustring.Make (runes);
  380. }
  381. /// <summary>
  382. /// Adds trailing whitespace or truncates <paramref name="text"/>
  383. /// so that it fits exactly <paramref name="width"/> console units.
  384. /// Note that some unicode characters take 2+ columns
  385. /// </summary>
  386. /// <param name="text"></param>
  387. /// <param name="width"></param>
  388. /// <returns></returns>
  389. public static string ClipOrPad (string text, int width)
  390. {
  391. if (string.IsNullOrEmpty (text))
  392. return text;
  393. // if value is not wide enough
  394. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  395. // pad it out with spaces to the given alignment
  396. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  397. return text + new string (' ', toPad);
  398. }
  399. // value is too wide
  400. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  401. }
  402. /// <summary>
  403. /// Formats the provided text to fit within the width provided using word wrapping.
  404. /// </summary>
  405. /// <param name="text">The text to word wrap</param>
  406. /// <param name="width">The width to contain the text to</param>
  407. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  408. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  409. /// <param name="tabWidth">The tab width.</param>
  410. /// <param name="textDirection">The text direction.</param>
  411. /// <returns>Returns a list of word wrapped lines.</returns>
  412. /// <remarks>
  413. /// <para>
  414. /// This method does not do any justification.
  415. /// </para>
  416. /// <para>
  417. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  418. /// </para>
  419. /// </remarks>
  420. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  421. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  422. {
  423. if (width < 0) {
  424. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  425. }
  426. int start = 0, end;
  427. var lines = new List<ustring> ();
  428. if (ustring.IsNullOrEmpty (text)) {
  429. return lines;
  430. }
  431. var runes = StripCRLF (text).ToRuneList ();
  432. if (!preserveTrailingSpaces) {
  433. if (IsHorizontalDirection (textDirection)) {
  434. while ((end = start + Math.Max (GetMaxLengthForWidth (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
  435. while (runes [end] != ' ' && end > start)
  436. end--;
  437. if (end == start)
  438. end = start + GetMaxLengthForWidth (runes.GetRange (end, runes.Count - end), width);
  439. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  440. start = end;
  441. if (runes [end] == ' ') {
  442. start++;
  443. }
  444. }
  445. } else {
  446. while ((end = start + width) < runes.Count) {
  447. while (runes [end] != ' ' && end > start)
  448. end--;
  449. if (end == start)
  450. end = start + width;
  451. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  452. start = end;
  453. if (runes [end] == ' ') {
  454. start++;
  455. }
  456. }
  457. }
  458. } else {
  459. while ((end = start) < runes.Count) {
  460. end = GetNextWhiteSpace (start, width, out bool incomplete);
  461. if (end == 0 && incomplete) {
  462. start = text.RuneCount;
  463. break;
  464. }
  465. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  466. start = end;
  467. if (incomplete) {
  468. start = text.RuneCount;
  469. break;
  470. }
  471. }
  472. }
  473. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  474. {
  475. var to = from;
  476. var length = cLength;
  477. incomplete = false;
  478. while (length < cWidth && to < runes.Count) {
  479. var rune = runes [to];
  480. if (IsHorizontalDirection (textDirection)) {
  481. length += Rune.ColumnWidth (rune);
  482. } else {
  483. length++;
  484. }
  485. if (length > cWidth) {
  486. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  487. incomplete = true;
  488. }
  489. return to;
  490. }
  491. if (rune == ' ') {
  492. if (length == cWidth) {
  493. return to + 1;
  494. } else if (length > cWidth) {
  495. return to;
  496. } else {
  497. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  498. }
  499. } else if (rune == '\t') {
  500. length += tabWidth + 1;
  501. if (length == tabWidth && tabWidth > cWidth) {
  502. return to + 1;
  503. } else if (length > cWidth && tabWidth > cWidth) {
  504. return to;
  505. } else {
  506. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  507. }
  508. }
  509. to++;
  510. }
  511. if (cLength > 0 && to < runes.Count && runes [to] != ' ') {
  512. return from;
  513. } else {
  514. return to;
  515. }
  516. }
  517. if (start < text.RuneCount) {
  518. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  519. }
  520. return lines;
  521. }
  522. /// <summary>
  523. /// Justifies text within a specified width.
  524. /// </summary>
  525. /// <param name="text">The text to justify.</param>
  526. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  527. /// <param name="talign">Alignment.</param>
  528. /// <param name="textDirection">The text direction.</param>
  529. /// <returns>Justified and clipped text.</returns>
  530. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  531. {
  532. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
  533. }
  534. /// <summary>
  535. /// Justifies text within a specified width.
  536. /// </summary>
  537. /// <param name="text">The text to justify.</param>
  538. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  539. /// <param name="justify">Justify.</param>
  540. /// <param name="textDirection">The text direction.</param>
  541. /// <returns>Justified and clipped text.</returns>
  542. public static ustring ClipAndJustify (ustring text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  543. {
  544. if (width < 0) {
  545. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  546. }
  547. if (ustring.IsNullOrEmpty (text)) {
  548. return text;
  549. }
  550. var runes = text.ToRuneList ();
  551. int slen = runes.Count;
  552. if (slen > width) {
  553. if (IsHorizontalDirection (textDirection)) {
  554. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  555. } else {
  556. return ustring.Make (runes.GetRange (0, width));
  557. }
  558. } else {
  559. if (justify) {
  560. return Justify (text, width, ' ', textDirection);
  561. } else if (IsHorizontalDirection (textDirection) && GetTextWidth (text) > width) {
  562. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  563. }
  564. return text;
  565. }
  566. }
  567. /// <summary>
  568. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  569. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  570. /// </summary>
  571. /// <param name="text"></param>
  572. /// <param name="width"></param>
  573. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  574. /// <param name="textDirection">The text direction.</param>
  575. /// <returns>The justified text.</returns>
  576. public static ustring Justify (ustring text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  577. {
  578. if (width < 0) {
  579. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  580. }
  581. if (ustring.IsNullOrEmpty (text)) {
  582. return text;
  583. }
  584. var words = text.Split (ustring.Make (' '));
  585. int textCount;
  586. if (IsHorizontalDirection (textDirection)) {
  587. textCount = words.Sum (arg => GetTextWidth (arg));
  588. } else {
  589. textCount = words.Sum (arg => arg.RuneCount);
  590. }
  591. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  592. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  593. var s = new System.Text.StringBuilder ();
  594. for (int w = 0; w < words.Length; w++) {
  595. var x = words [w];
  596. s.Append (x);
  597. if (w + 1 < words.Length)
  598. for (int i = 0; i < spaces; i++)
  599. s.Append (spaceChar);
  600. if (extras > 0) {
  601. extras--;
  602. }
  603. }
  604. return ustring.Make (s.ToString ());
  605. }
  606. static char [] whitespace = new char [] { ' ', '\t' };
  607. private int hotKeyPos;
  608. /// <summary>
  609. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  610. /// </summary>
  611. /// <param name="text"></param>
  612. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  613. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  614. /// <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>
  615. /// <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>
  616. /// <param name="tabWidth">The tab width.</param>
  617. /// <param name="textDirection">The text direction.</param>
  618. /// <returns>A list of word wrapped lines.</returns>
  619. /// <remarks>
  620. /// <para>
  621. /// An empty <c>text</c> string will result in one empty line.
  622. /// </para>
  623. /// <para>
  624. /// If <c>width</c> is 0, a single, empty line will be returned.
  625. /// </para>
  626. /// <para>
  627. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  628. /// </para>
  629. /// </remarks>
  630. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  631. {
  632. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  633. }
  634. /// <summary>
  635. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  636. /// </summary>
  637. /// <param name="text"></param>
  638. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  639. /// <param name="justify">Specifies whether the text should be justified.</param>
  640. /// <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>
  641. /// <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>
  642. /// <param name="tabWidth">The tab width.</param>
  643. /// <param name="textDirection">The text direction.</param>
  644. /// <returns>A list of word wrapped lines.</returns>
  645. /// <remarks>
  646. /// <para>
  647. /// An empty <c>text</c> string will result in one empty line.
  648. /// </para>
  649. /// <para>
  650. /// If <c>width</c> is 0, a single, empty line will be returned.
  651. /// </para>
  652. /// <para>
  653. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  654. /// </para>
  655. /// </remarks>
  656. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  657. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  658. {
  659. if (width < 0) {
  660. throw new ArgumentOutOfRangeException ("width cannot be negative");
  661. }
  662. List<ustring> lineResult = new List<ustring> ();
  663. if (ustring.IsNullOrEmpty (text) || width == 0) {
  664. lineResult.Add (ustring.Empty);
  665. return lineResult;
  666. }
  667. if (wordWrap == false) {
  668. text = ReplaceCRLFWithSpace (text);
  669. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  670. return lineResult;
  671. }
  672. var runes = text.ToRuneList ();
  673. int runeCount = runes.Count;
  674. int lp = 0;
  675. for (int i = 0; i < runeCount; i++) {
  676. Rune c = runes [i];
  677. if (c == '\n') {
  678. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  679. foreach (var line in wrappedLines) {
  680. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  681. }
  682. if (wrappedLines.Count == 0) {
  683. lineResult.Add (ustring.Empty);
  684. }
  685. lp = i + 1;
  686. }
  687. }
  688. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  689. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  690. }
  691. return lineResult;
  692. }
  693. /// <summary>
  694. /// Computes the number of lines needed to render the specified text given the width.
  695. /// </summary>
  696. /// <returns>Number of lines.</returns>
  697. /// <param name="text">Text, may contain newlines.</param>
  698. /// <param name="width">The minimum width for the text.</param>
  699. public static int MaxLines (ustring text, int width)
  700. {
  701. var result = TextFormatter.Format (text, width, false, true);
  702. return result.Count;
  703. }
  704. /// <summary>
  705. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  706. /// </summary>
  707. /// <returns>Max width of lines.</returns>
  708. /// <param name="text">Text, may contain newlines.</param>
  709. /// <param name="width">The minimum width for the text.</param>
  710. public static int MaxWidth (ustring text, int width)
  711. {
  712. var result = TextFormatter.Format (text, width, false, true);
  713. var max = 0;
  714. result.ForEach (s => {
  715. var m = 0;
  716. s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
  717. if (m > max) {
  718. max = m;
  719. }
  720. });
  721. return max;
  722. }
  723. /// <summary>
  724. /// Gets the total width of the passed text.
  725. /// </summary>
  726. /// <param name="text"></param>
  727. /// <returns>The text width.</returns>
  728. public static int GetTextWidth (ustring text)
  729. {
  730. return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
  731. }
  732. /// <summary>
  733. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  734. /// and the <paramref name="length"/>.
  735. /// </summary>
  736. /// <param name="lines">The lines.</param>
  737. /// <param name="startIndex">The start index.</param>
  738. /// <param name="length">The length.</param>
  739. /// <returns>The maximum characters width.</returns>
  740. public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
  741. {
  742. var max = 0;
  743. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  744. var runes = lines [i];
  745. if (runes.Length > 0)
  746. max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
  747. }
  748. return max;
  749. }
  750. /// <summary>
  751. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  752. /// and the <paramref name="length"/>.
  753. /// </summary>
  754. /// <param name="text">The text.</param>
  755. /// <param name="startIndex">The start index.</param>
  756. /// <param name="length">The length.</param>
  757. /// <returns>The maximum characters width.</returns>
  758. public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
  759. {
  760. var max = 0;
  761. var runes = text.ToRunes ();
  762. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  763. max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
  764. }
  765. return max;
  766. }
  767. /// <summary>
  768. /// Gets the index position from the text based on the <paramref name="width"/>.
  769. /// </summary>
  770. /// <param name="text">The text.</param>
  771. /// <param name="width">The width.</param>
  772. /// <returns>The index of the text that fit the width.</returns>
  773. public static int GetMaxLengthForWidth (ustring text, int width)
  774. {
  775. var runes = text.ToRuneList ();
  776. var runesLength = 0;
  777. var runeIdx = 0;
  778. for (; runeIdx < runes.Count; runeIdx++) {
  779. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  780. if (runesLength + runeWidth > width) {
  781. break;
  782. }
  783. runesLength += runeWidth;
  784. }
  785. return runeIdx;
  786. }
  787. /// <summary>
  788. /// Gets the index position from the list based on the <paramref name="width"/>.
  789. /// </summary>
  790. /// <param name="runes">The runes.</param>
  791. /// <param name="width">The width.</param>
  792. /// <returns>The index of the list that fit the width.</returns>
  793. public static int GetMaxLengthForWidth (List<Rune> runes, int width)
  794. {
  795. var runesLength = 0;
  796. var runeIdx = 0;
  797. for (; runeIdx < runes.Count; runeIdx++) {
  798. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  799. if (runesLength + runeWidth > width) {
  800. break;
  801. }
  802. runesLength += runeWidth;
  803. }
  804. return runeIdx;
  805. }
  806. /// <summary>
  807. /// Gets the index position from the list based on the <paramref name="width"/>.
  808. /// </summary>
  809. /// <param name="lines">The lines.</param>
  810. /// <param name="width">The width.</param>
  811. /// <returns>The index of the list that fit the width.</returns>
  812. public static int GetMaxColsForWidth (List<ustring> lines, int width)
  813. {
  814. var runesLength = 0;
  815. var lineIdx = 0;
  816. for (; lineIdx < lines.Count; lineIdx++) {
  817. var runes = lines [lineIdx].ToRuneList ();
  818. var maxRruneWidth = runes.Count > 0
  819. ? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
  820. if (runesLength + maxRruneWidth > width) {
  821. break;
  822. }
  823. runesLength += maxRruneWidth;
  824. }
  825. return lineIdx;
  826. }
  827. /// <summary>
  828. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  829. /// </summary>
  830. /// <param name="x">The x location of the rectangle</param>
  831. /// <param name="y">The y location of the rectangle</param>
  832. /// <param name="text">The text to measure</param>
  833. /// <param name="direction">The text direction.</param>
  834. /// <returns></returns>
  835. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  836. {
  837. if (ustring.IsNullOrEmpty (text)) {
  838. return new Rect (new Point (x, y), Size.Empty);
  839. }
  840. int w, h;
  841. if (IsHorizontalDirection (direction)) {
  842. int mw = 0;
  843. int ml = 1;
  844. int cols = 0;
  845. foreach (var rune in text) {
  846. if (rune == '\n') {
  847. ml++;
  848. if (cols > mw) {
  849. mw = cols;
  850. }
  851. cols = 0;
  852. } else if (rune != '\r') {
  853. cols++;
  854. var rw = Rune.ColumnWidth (rune);
  855. if (rw > 0) {
  856. rw--;
  857. }
  858. cols += rw;
  859. }
  860. }
  861. if (cols > mw) {
  862. mw = cols;
  863. }
  864. w = mw;
  865. h = ml;
  866. } else {
  867. int vw = 0;
  868. int vh = 0;
  869. int rows = 0;
  870. foreach (var rune in text) {
  871. if (rune == '\n') {
  872. vw++;
  873. if (rows > vh) {
  874. vh = rows;
  875. }
  876. rows = 0;
  877. } else if (rune != '\r') {
  878. rows++;
  879. var rw = Rune.ColumnWidth (rune);
  880. if (rw < 0) {
  881. rw++;
  882. }
  883. if (rw > vw) {
  884. vw = rw;
  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. }