TextFormatter.cs 42 KB

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