TextFormatter.cs 42 KB

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