TextFormatter.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Text alignment enumeration, controls how text is displayed.
  8. /// </summary>
  9. public enum TextAlignment {
  10. /// <summary>
  11. /// The text will be left-aligned.
  12. /// </summary>
  13. Left,
  14. /// <summary>
  15. /// The text will be right-aligned.
  16. /// </summary>
  17. Right,
  18. /// <summary>
  19. /// The text will be centered horizontally.
  20. /// </summary>
  21. Centered,
  22. /// <summary>
  23. /// The text will be justified (spaces will be added to existing spaces such that
  24. /// the text fills the container horizontally).
  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. /// The text will be top-aligned.
  34. /// </summary>
  35. Top,
  36. /// <summary>
  37. /// The text will be bottom-aligned.
  38. /// </summary>
  39. Bottom,
  40. /// <summary>
  41. /// The text will centered vertically.
  42. /// </summary>
  43. Middle,
  44. /// <summary>
  45. /// The text will be justified (spaces will be added to existing spaces such that
  46. /// the text fills the container vertically).
  47. /// </summary>
  48. Justified
  49. }
  50. /// TextDirection [H] = Horizontal [V] = Vertical
  51. /// =============
  52. /// LeftRight_TopBottom [H] Normal
  53. /// TopBottom_LeftRight [V] Normal
  54. ///
  55. /// RightLeft_TopBottom [H] Invert Text
  56. /// TopBottom_RightLeft [V] Invert Lines
  57. ///
  58. /// LeftRight_BottomTop [H] Invert Lines
  59. /// BottomTop_LeftRight [V] Invert Text
  60. ///
  61. /// RightLeft_BottomTop [H] Invert Text + Invert Lines
  62. /// BottomTop_RightLeft [V] Invert Text + Invert Lines
  63. ///
  64. /// <summary>
  65. /// Text direction enumeration, controls how text is displayed.
  66. /// </summary>
  67. public enum TextDirection {
  68. /// <summary>
  69. /// Normal horizontal direction.
  70. /// <code>HELLO<br/>WORLD</code>
  71. /// </summary>
  72. LeftRight_TopBottom,
  73. /// <summary>
  74. /// Normal vertical direction.
  75. /// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
  76. /// </summary>
  77. TopBottom_LeftRight,
  78. /// <summary>
  79. /// This is a horizontal direction. <br/> RTL
  80. /// <code>OLLEH<br/>DLROW</code>
  81. /// </summary>
  82. RightLeft_TopBottom,
  83. /// <summary>
  84. /// This is a vertical direction.
  85. /// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
  86. /// </summary>
  87. TopBottom_RightLeft,
  88. /// <summary>
  89. /// This is a horizontal direction.
  90. /// <code>WORLD<br/>HELLO</code>
  91. /// </summary>
  92. LeftRight_BottomTop,
  93. /// <summary>
  94. /// This is a vertical direction.
  95. /// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
  96. /// </summary>
  97. BottomTop_LeftRight,
  98. /// <summary>
  99. /// This is a horizontal direction.
  100. /// <code>DLROW<br/>OLLEH</code>
  101. /// </summary>
  102. RightLeft_BottomTop,
  103. /// <summary>
  104. /// This is a vertical direction.
  105. /// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
  106. /// </summary>
  107. BottomTop_RightLeft
  108. }
  109. /// <summary>
  110. /// Provides text formatting. Supports <see cref="View.HotKey"/>s, horizontal alignment, vertical alignment, multiple lines, and word-based line wrap.
  111. /// </summary>
  112. public class TextFormatter {
  113. #region Static Members
  114. static string StripCRLF (string str, bool keepNewLine = false)
  115. {
  116. var runes = str.ToRuneList ();
  117. for (int i = 0; i < runes.Count; i++) {
  118. switch ((char)runes [i].Value) {
  119. case '\n':
  120. if (!keepNewLine) {
  121. runes.RemoveAt (i);
  122. }
  123. break;
  124. case '\r':
  125. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  126. runes.RemoveAt (i);
  127. if (!keepNewLine) {
  128. runes.RemoveAt (i);
  129. }
  130. i++;
  131. } else {
  132. if (!keepNewLine) {
  133. runes.RemoveAt (i);
  134. }
  135. }
  136. break;
  137. }
  138. }
  139. return StringExtensions.ToString (runes);
  140. }
  141. static string ReplaceCRLFWithSpace (string str)
  142. {
  143. var runes = str.ToRuneList ();
  144. for (int i = 0; i < runes.Count; i++) {
  145. switch (runes [i].Value) {
  146. case '\n':
  147. runes [i] = (Rune)' ';
  148. break;
  149. case '\r':
  150. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  151. runes [i] = (Rune)' ';
  152. runes.RemoveAt (i + 1);
  153. i++;
  154. } else {
  155. runes [i] = (Rune)' ';
  156. }
  157. break;
  158. }
  159. }
  160. return StringExtensions.ToString (runes);
  161. }
  162. static string ReplaceTABWithSpaces (string str, int tabWidth)
  163. {
  164. if (tabWidth == 0) {
  165. return str.Replace ("\t", "");
  166. }
  167. return str.Replace ("\t", new string (' ', tabWidth));
  168. }
  169. /// <summary>
  170. /// Splits all newlines in the <paramref name="text"/> into a list
  171. /// and supports both CRLF and LF, preserving the ending newline.
  172. /// </summary>
  173. /// <param name="text">The text.</param>
  174. /// <returns>A list of text without the newline characters.</returns>
  175. public static List<string> SplitNewLine (string text)
  176. {
  177. var runes = text.ToRuneList ();
  178. var lines = new List<string> ();
  179. var start = 0;
  180. var end = 0;
  181. for (int i = 0; i < runes.Count; i++) {
  182. end = i;
  183. switch (runes [i].Value) {
  184. case '\n':
  185. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  186. i++;
  187. start = i;
  188. break;
  189. case '\r':
  190. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  191. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  192. i += 2;
  193. start = i;
  194. } else {
  195. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  196. i++;
  197. start = i;
  198. }
  199. break;
  200. }
  201. }
  202. if (runes.Count > 0 && lines.Count == 0) {
  203. lines.Add (StringExtensions.ToString (runes));
  204. } else if (runes.Count > 0 && start < runes.Count) {
  205. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  206. } else {
  207. lines.Add ("");
  208. }
  209. return lines;
  210. }
  211. /// <summary>
  212. /// Adds trailing whitespace or truncates <paramref name="text"/>
  213. /// so that it fits exactly <paramref name="width"/> console units.
  214. /// Note that some unicode characters take 2+ columns
  215. /// </summary>
  216. /// <param name="text"></param>
  217. /// <param name="width"></param>
  218. /// <returns></returns>
  219. public static string ClipOrPad (string text, int width)
  220. {
  221. if (string.IsNullOrEmpty (text))
  222. return text;
  223. // if value is not wide enough
  224. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width) {
  225. // pad it out with spaces to the given alignment
  226. int toPad = width - (text.EnumerateRunes ().Sum (c => c.GetColumns ()));
  227. return text + new string (' ', toPad);
  228. }
  229. // value is too wide
  230. return new string (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  231. }
  232. /// <summary>
  233. /// Formats the provided text to fit within the width provided using word wrapping.
  234. /// </summary>
  235. /// <param name="text">The text to word wrap</param>
  236. /// <param name="width">The number of columns to constrain the text to</param>
  237. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  238. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  239. /// <param name="tabWidth">The number of columns used for a tab.</param>
  240. /// <param name="textDirection">The text direction.</param>
  241. /// <returns>A list of word wrapped lines.</returns>
  242. /// <remarks>
  243. /// <para>
  244. /// This method does not do any justification.
  245. /// </para>
  246. /// <para>
  247. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  248. /// </para>
  249. /// <para>
  250. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved at the end of the last line.
  251. /// </para>
  252. /// </remarks>
  253. public static List<string> WordWrapText (string text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  254. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  255. {
  256. if (width < 0) {
  257. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  258. }
  259. int start = 0, end;
  260. var lines = new List<string> ();
  261. if (string.IsNullOrEmpty (text)) {
  262. return lines;
  263. }
  264. var runes = StripCRLF (text).ToRuneList ();
  265. if (preserveTrailingSpaces) {
  266. while ((end = start) < runes.Count) {
  267. end = GetNextWhiteSpace (start, width, out bool incomplete);
  268. if (end == 0 && incomplete) {
  269. start = text.GetRuneCount ();
  270. break;
  271. }
  272. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  273. start = end;
  274. if (incomplete) {
  275. start = text.GetRuneCount ();
  276. break;
  277. }
  278. }
  279. } else {
  280. if (IsHorizontalDirection (textDirection)) {
  281. //if (GetLengthThatFits (runes.GetRange (start, runes.Count - start), width) > 0) {
  282. // // while there's still runes left and end is not past end...
  283. // while (start < runes.Count &&
  284. // (end = start + Math.Max (GetLengthThatFits (runes.GetRange (start, runes.Count - start), width) - 1, 0)) < runes.Count) {
  285. // // end now points to start + LengthThatFits
  286. // // Walk back over trailing spaces
  287. // while (runes [end] == ' ' && end > start) {
  288. // end--;
  289. // }
  290. // // end now points to start + LengthThatFits - any trailing spaces; start saving new line
  291. // var line = runes.GetRange (start, end - start + 1);
  292. // if (end == start && width > 1) {
  293. // // it was all trailing spaces; now walk forward to next non-space
  294. // do {
  295. // start++;
  296. // } while (start < runes.Count && runes [start] == ' ');
  297. // // start now points to first non-space we haven't seen yet or we're done
  298. // if (start < runes.Count) {
  299. // // we're not done. we have remaining = width - line.Count columns left;
  300. // var remaining = width - line.Count;
  301. // if (remaining > 1) {
  302. // // add a space for all the spaces we walked over
  303. // line.Add (' ');
  304. // }
  305. // var count = GetLengthThatFits (runes.GetRange (start, runes.Count - start), width - line.Count);
  306. // // [start..count] now has rest of line
  307. // line.AddRange (runes.GetRange (start, count));
  308. // start += count;
  309. // }
  310. // } else {
  311. // start += line.Count;
  312. // }
  313. // //// if the previous line was just a ' ' and the new line is just a ' '
  314. // //// don't add new line
  315. // //if (line [0] == ' ' && (lines.Count > 0 && lines [lines.Count - 1] [0] == ' ')) {
  316. // //} else {
  317. // //}
  318. // lines.Add (string.Make (line));
  319. // // move forward to next non-space
  320. // while (width > 1 && start < runes.Count && runes [start] == ' ') {
  321. // start++;
  322. // }
  323. // }
  324. //}
  325. while ((end = start + GetLengthThatFits (runes.GetRange (start, runes.Count - start), width, tabWidth)) < runes.Count) {
  326. while (runes [end].Value != ' ' && end > start)
  327. end--;
  328. if (end == start)
  329. end = start + GetLengthThatFits (runes.GetRange (end, runes.Count - end), width, tabWidth);
  330. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  331. if (end > start && GetRuneWidth (str, tabWidth) <= width) {
  332. lines.Add (str);
  333. start = end;
  334. if (runes [end].Value == ' ') {
  335. start++;
  336. }
  337. } else {
  338. end++;
  339. start = end;
  340. }
  341. }
  342. } else {
  343. while ((end = start + width) < runes.Count) {
  344. while (runes [end].Value != ' ' && end > start) {
  345. end--;
  346. }
  347. if (end == start) {
  348. end = start + width;
  349. }
  350. var zeroLength = 0;
  351. for (int i = end; i < runes.Count - start; i++) {
  352. var r = runes [i];
  353. if (r.GetColumns () == 0) {
  354. zeroLength++;
  355. } else {
  356. break;
  357. }
  358. }
  359. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start + zeroLength)));
  360. end += zeroLength;
  361. start = end;
  362. if (runes [end].Value == ' ') {
  363. start++;
  364. }
  365. }
  366. }
  367. }
  368. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  369. {
  370. var lastFrom = from;
  371. var to = from;
  372. var length = cLength;
  373. incomplete = false;
  374. while (length < cWidth && to < runes.Count) {
  375. var rune = runes [to];
  376. if (IsHorizontalDirection (textDirection)) {
  377. length += rune.GetColumns ();
  378. } else {
  379. length++;
  380. }
  381. if (length > cWidth) {
  382. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  383. incomplete = true;
  384. }
  385. return to;
  386. }
  387. if (rune.Value == ' ') {
  388. if (length == cWidth) {
  389. return to + 1;
  390. } else if (length > cWidth) {
  391. return to;
  392. } else {
  393. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  394. }
  395. } else if (rune.Value == '\t') {
  396. length += tabWidth + 1;
  397. if (length == tabWidth && tabWidth > cWidth) {
  398. return to + 1;
  399. } else if (length > cWidth && tabWidth > cWidth) {
  400. return to;
  401. } else {
  402. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  403. }
  404. }
  405. to++;
  406. }
  407. if (cLength > 0 && to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t') {
  408. return from;
  409. } else if (cLength > 0 && to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t')) {
  410. return lastFrom;
  411. } else {
  412. return to;
  413. }
  414. }
  415. if (start < text.GetRuneCount ()) {
  416. var str = ReplaceTABWithSpaces (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)), tabWidth);
  417. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || (!preserveTrailingSpaces && str.GetColumns () <= width)) {
  418. lines.Add (str);
  419. }
  420. }
  421. return lines;
  422. }
  423. /// <summary>
  424. /// Justifies text within a specified width.
  425. /// </summary>
  426. /// <param name="text">The text to justify.</param>
  427. /// <param name="width">The number of columns to clip the text to. Text longer than <paramref name="width"/> will be clipped.</param>
  428. /// <param name="talign">Alignment.</param>
  429. /// <param name="textDirection">The text direction.</param>
  430. /// <param name="tabWidth">The number of columns used for a tab.</param>
  431. /// <returns>Justified and clipped text.</returns>
  432. public static string ClipAndJustify (string text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom, int tabWidth = 0)
  433. {
  434. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection, tabWidth);
  435. }
  436. /// <summary>
  437. /// Justifies text within a specified width.
  438. /// </summary>
  439. /// <param name="text">The text to justify.</param>
  440. /// <param name="width">The number of columns to clip the text to. Text longer than <paramref name="width"/> will be clipped.</param>
  441. /// <param name="justify">Justify.</param>
  442. /// <param name="textDirection">The text direction.</param>
  443. /// <param name="tabWidth">The number of columns used for a tab.</param>
  444. /// <returns>Justified and clipped text.</returns>
  445. public static string ClipAndJustify (string text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom, int tabWidth = 0)
  446. {
  447. if (width < 0) {
  448. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  449. }
  450. if (string.IsNullOrEmpty (text)) {
  451. return text;
  452. }
  453. text = ReplaceTABWithSpaces (text, tabWidth);
  454. var runes = text.ToRuneList ();
  455. int slen = runes.Count;
  456. if (slen > width) {
  457. if (IsHorizontalDirection (textDirection)) {
  458. return StringExtensions.ToString (runes.GetRange (0, GetLengthThatFits (text, width, tabWidth)));
  459. } else {
  460. var zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  461. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  462. }
  463. } else {
  464. if (justify) {
  465. return Justify (text, width, ' ', textDirection, tabWidth);
  466. } else if (IsHorizontalDirection (textDirection) && GetRuneWidth (text, tabWidth) > width) {
  467. return StringExtensions.ToString (runes.GetRange (0, GetLengthThatFits (text, width, tabWidth)));
  468. }
  469. return text;
  470. }
  471. }
  472. /// <summary>
  473. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  474. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  475. /// </summary>
  476. /// <param name="text"></param>
  477. /// <param name="width"></param>
  478. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  479. /// <param name="textDirection">The text direction.</param>
  480. /// <param name="tabWidth">The number of columns used for a tab.</param>
  481. /// <returns>The justified text.</returns>
  482. public static string Justify (string text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom, int tabWidth = 0)
  483. {
  484. if (width < 0) {
  485. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  486. }
  487. if (string.IsNullOrEmpty (text)) {
  488. return text;
  489. }
  490. text = ReplaceTABWithSpaces (text, tabWidth);
  491. var words = text.Split (' ');
  492. int textCount;
  493. if (IsHorizontalDirection (textDirection)) {
  494. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth));
  495. } else {
  496. textCount = words.Sum (arg => arg.GetRuneCount ());
  497. }
  498. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  499. var extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  500. var s = new System.Text.StringBuilder ();
  501. for (int w = 0; w < words.Length; w++) {
  502. var x = words [w];
  503. s.Append (x);
  504. if (w + 1 < words.Length)
  505. for (int i = 0; i < spaces; i++)
  506. s.Append (spaceChar);
  507. if (extras > 0) {
  508. for (int i = 0; i < 1; i++)
  509. s.Append (spaceChar);
  510. extras--;
  511. }
  512. if (w + 1 == words.Length - 1) {
  513. for (int i = 0; i < extras; i++)
  514. s.Append (spaceChar);
  515. }
  516. }
  517. return s.ToString ();
  518. }
  519. //static char [] whitespace = new char [] { ' ', '\t' };
  520. /// <summary>
  521. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  522. /// </summary>
  523. /// <param name="text"></param>
  524. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  525. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  526. /// <param name="wordWrap">If <see langword="true"/>, the text will be wrapped to new lines no longer than <paramref name="width"/>.
  527. /// If <see langword="false"/>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <paramref name="width"/>.</param>
  528. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  529. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  530. /// <param name="tabWidth">The number of columns used for a tab.</param>
  531. /// <param name="textDirection">The text direction.</param>
  532. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  533. /// <returns>A list of word wrapped lines.</returns>
  534. /// <remarks>
  535. /// <para>
  536. /// An empty <paramref name="text"/> string will result in one empty line.
  537. /// </para>
  538. /// <para>
  539. /// If <paramref name="width"/> is 0, a single, empty line will be returned.
  540. /// </para>
  541. /// <para>
  542. /// If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.
  543. /// </para>
  544. /// </remarks>
  545. public static List<string> Format (string text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom, bool multiLine = false)
  546. {
  547. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection, multiLine);
  548. }
  549. /// <summary>
  550. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  551. /// </summary>
  552. /// <param name="text"></param>
  553. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  554. /// <param name="justify">Specifies whether the text should be justified.</param>
  555. /// <param name="wordWrap">If <see langword="true"/>, the text will be wrapped to new lines no longer than <paramref name="width"/>.
  556. /// If <see langword="false"/>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <paramref name="width"/>.</param>
  557. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  558. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  559. /// <param name="tabWidth">The number of columns used for a tab.</param>
  560. /// <param name="textDirection">The text direction.</param>
  561. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  562. /// <returns>A list of word wrapped lines.</returns>
  563. /// <remarks>
  564. /// <para>
  565. /// An empty <paramref name="text"/> string will result in one empty line.
  566. /// </para>
  567. /// <para>
  568. /// If <paramref name="width"/> is 0, a single, empty line will be returned.
  569. /// </para>
  570. /// <para>
  571. /// If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.
  572. /// </para>
  573. /// </remarks>
  574. public static List<string> Format (string text, int width, bool justify, bool wordWrap,
  575. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom, bool multiLine = false)
  576. {
  577. if (width < 0) {
  578. throw new ArgumentOutOfRangeException ("width cannot be negative");
  579. }
  580. List<string> lineResult = new List<string> ();
  581. if (string.IsNullOrEmpty (text) || width == 0) {
  582. lineResult.Add (string.Empty);
  583. return lineResult;
  584. }
  585. if (!wordWrap) {
  586. text = ReplaceTABWithSpaces (text, tabWidth);
  587. if (multiLine) {
  588. string [] lines = null;
  589. if (text.Contains ("\r\n")) {
  590. lines = text.Split ("\r\n");
  591. } else if (text.Contains ('\n')) {
  592. lines = text.Split ('\n');
  593. }
  594. if (lines == null) {
  595. lines = new [] { text };
  596. }
  597. foreach (var line in lines) {
  598. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  599. }
  600. return lineResult;
  601. } else {
  602. text = ReplaceCRLFWithSpace (text);
  603. lineResult.Add (ClipAndJustify (text, width, justify, textDirection, tabWidth));
  604. return lineResult;
  605. }
  606. }
  607. var runes = StripCRLF (text, true).ToRuneList ();
  608. int runeCount = runes.Count;
  609. int lp = 0;
  610. for (int i = 0; i < runeCount; i++) {
  611. Rune c = runes [i];
  612. if (c.Value == '\n') {
  613. var wrappedLines = WordWrapText (StringExtensions.ToString (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  614. foreach (var line in wrappedLines) {
  615. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  616. }
  617. if (wrappedLines.Count == 0) {
  618. lineResult.Add (string.Empty);
  619. }
  620. lp = i + 1;
  621. }
  622. }
  623. foreach (var line in WordWrapText (StringExtensions.ToString (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  624. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  625. }
  626. return lineResult;
  627. }
  628. /// <summary>
  629. /// Computes the number of lines needed to render the specified text given the width.
  630. /// </summary>
  631. /// <returns>Number of lines.</returns>
  632. /// <param name="text">Text, may contain newlines.</param>
  633. /// <param name="width">The minimum width for the text.</param>
  634. public static int MaxLines (string text, int width)
  635. {
  636. var result = TextFormatter.Format (text, width, false, true);
  637. return result.Count;
  638. }
  639. /// <summary>
  640. /// Computes the maximum width needed to render the text (single line or multiple lines, word wrapped) given
  641. /// a number of columns to constrain the text to.
  642. /// </summary>
  643. /// <returns>Width of the longest line after formatting the text constrained by <paramref name="maxColumns"/>.</returns>
  644. /// <param name="text">Text, may contain newlines.</param>
  645. /// <param name="maxColumns">The number of columns to constrain the text to for formatting.</param>
  646. /// <param name="tabWidth">The number of columns used for a tab.</param>
  647. public static int MaxWidth (string text, int maxColumns, int tabWidth = 0)
  648. {
  649. var result = TextFormatter.Format (text: text, width: maxColumns, justify: false, wordWrap: true);
  650. var max = 0;
  651. result.ForEach (s => {
  652. var m = 0;
  653. s.ToRuneList ().ForEach (r => m += GetRuneWidth (r, tabWidth));
  654. if (m > max) {
  655. max = m;
  656. }
  657. });
  658. return max;
  659. }
  660. /// <summary>
  661. /// Returns the width of the widest line in the text, accounting for wide-glyphs (uses <see cref="StringExtensions.GetColumns"/>).
  662. /// <paramref name="text"/> if it contains newlines.
  663. /// </summary>
  664. /// <param name="text">Text, may contain newlines.</param>
  665. /// <param name="tabWidth">The number of columns used for a tab.</param>
  666. /// <returns>The length of the longest line.</returns>
  667. public static int MaxWidthLine (string text, int tabWidth = 0)
  668. {
  669. var result = TextFormatter.SplitNewLine (text);
  670. return result.Max (x => GetRuneWidth (x, tabWidth));
  671. }
  672. /// <summary>
  673. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  674. /// and the <paramref name="length"/>.
  675. /// </summary>
  676. /// <param name="lines">The lines.</param>
  677. /// <param name="startIndex">The start index.</param>
  678. /// <param name="length">The length.</param>
  679. /// <param name="tabWidth">The number of columns used for a tab.</param>
  680. /// <returns>The maximum characters width.</returns>
  681. public static int GetSumMaxCharWidth (List<string> lines, int startIndex = -1, int length = -1, int tabWidth = 0)
  682. {
  683. var max = 0;
  684. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  685. var runes = lines [i];
  686. if (runes.Length > 0)
  687. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  688. }
  689. return max;
  690. }
  691. /// <summary>
  692. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  693. /// and the <paramref name="length"/>.
  694. /// </summary>
  695. /// <param name="text">The text.</param>
  696. /// <param name="startIndex">The start index.</param>
  697. /// <param name="length">The length.</param>
  698. /// <param name="tabWidth">The number of columns used for a tab.</param>
  699. /// <returns>The maximum characters width.</returns>
  700. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  701. {
  702. var max = 0;
  703. var runes = text.ToRunes ();
  704. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  705. max += GetRuneWidth (runes [i], tabWidth);
  706. }
  707. return max;
  708. }
  709. /// <summary>
  710. /// Gets the number of the Runes in a <see cref="string"/> that will fit in <paramref name="columns"/>.
  711. /// </summary>
  712. /// <param name="text">The text.</param>
  713. /// <param name="columns">The width.</param>
  714. /// <param name="tabWidth">The number of columns used for a tab.</param>
  715. /// <returns>The index of the text that fit the width.</returns>
  716. public static int GetLengthThatFits (string text, int columns, int tabWidth = 0) => GetLengthThatFits (text?.ToRuneList (), columns, tabWidth);
  717. /// <summary>
  718. /// Gets the number of the Runes in a list of Runes that will fit in <paramref name="columns"/>.
  719. /// </summary>
  720. /// <param name="runes">The list of runes.</param>
  721. /// <param name="columns">The width.</param>
  722. /// <param name="tabWidth">The number of columns used for a tab.</param>
  723. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="columns"/>.</returns>
  724. public static int GetLengthThatFits (List<Rune> runes, int columns, int tabWidth = 0)
  725. {
  726. if (runes == null || runes.Count == 0) {
  727. return 0;
  728. }
  729. var runesLength = 0;
  730. var runeIdx = 0;
  731. for (; runeIdx < runes.Count; runeIdx++) {
  732. var runeWidth = GetRuneWidth (runes [runeIdx], tabWidth);
  733. if (runesLength + runeWidth > columns) {
  734. break;
  735. }
  736. runesLength += runeWidth;
  737. }
  738. return runeIdx;
  739. }
  740. private static int GetRuneWidth (string str, int tabWidth)
  741. {
  742. return GetRuneWidth (str.EnumerateRunes ().ToList (), tabWidth);
  743. }
  744. private static int GetRuneWidth (List<Rune> runes, int tabWidth)
  745. {
  746. return runes.Sum (r => GetRuneWidth (r, tabWidth));
  747. }
  748. private static int GetRuneWidth (Rune rune, int tabWidth)
  749. {
  750. var runeWidth = rune.GetColumns ();
  751. if (rune.Value == '\t') {
  752. return tabWidth;
  753. }
  754. if (runeWidth < 0 || runeWidth > 0) {
  755. return Math.Max (runeWidth, 1);
  756. }
  757. return runeWidth;
  758. }
  759. /// <summary>
  760. /// Gets the index position from the list based on the <paramref name="width"/>.
  761. /// </summary>
  762. /// <param name="lines">The lines.</param>
  763. /// <param name="width">The width.</param>
  764. /// <param name="tabWidth">The number of columns used for a tab.</param>
  765. /// <returns>The index of the list that fit the width.</returns>
  766. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  767. {
  768. var runesLength = 0;
  769. var lineIdx = 0;
  770. for (; lineIdx < lines.Count; lineIdx++) {
  771. var runes = lines [lineIdx].ToRuneList ();
  772. var maxRruneWidth = runes.Count > 0
  773. ? runes.Max (r => GetRuneWidth (r, tabWidth)) : 1;
  774. if (runesLength + maxRruneWidth > width) {
  775. break;
  776. }
  777. runesLength += maxRruneWidth;
  778. }
  779. return lineIdx;
  780. }
  781. /// <summary>
  782. /// Calculates the rectangle required to hold text, assuming no word wrapping or justification.
  783. /// </summary>
  784. /// <param name="x">The x location of the rectangle</param>
  785. /// <param name="y">The y location of the rectangle</param>
  786. /// <param name="text">The text to measure</param>
  787. /// <param name="direction">The text direction.</param>
  788. /// <param name="tabWidth">The number of columns used for a tab.</param>
  789. /// <returns></returns>
  790. public static Rect CalcRect (int x, int y, string text, TextDirection direction = TextDirection.LeftRight_TopBottom, int tabWidth = 0)
  791. {
  792. if (string.IsNullOrEmpty (text)) {
  793. return new Rect (new Point (x, y), Size.Empty);
  794. }
  795. int w, h;
  796. if (IsHorizontalDirection (direction)) {
  797. int mw = 0;
  798. int ml = 1;
  799. int cols = 0;
  800. foreach (var rune in text.EnumerateRunes ()) {
  801. if (rune.Value == '\n') {
  802. ml++;
  803. if (cols > mw) {
  804. mw = cols;
  805. }
  806. cols = 0;
  807. } else if (rune.Value != '\r') {
  808. cols++;
  809. var rw = 0;
  810. if (rune.Value == '\t') {
  811. rw += tabWidth - 1;
  812. } else {
  813. rw = ((Rune)rune).GetColumns ();
  814. if (rw > 0) {
  815. rw--;
  816. } else if (rw == 0) {
  817. cols--;
  818. }
  819. }
  820. cols += rw;
  821. }
  822. }
  823. if (cols > mw) {
  824. mw = cols;
  825. }
  826. w = mw;
  827. h = ml;
  828. } else {
  829. int vw = 1, cw = 1;
  830. int vh = 0;
  831. int rows = 0;
  832. foreach (var rune in text.EnumerateRunes ()) {
  833. if (rune.Value == '\n') {
  834. vw++;
  835. if (rows > vh) {
  836. vh = rows;
  837. }
  838. rows = 0;
  839. cw = 1;
  840. } else if (rune.Value != '\r') {
  841. rows++;
  842. var rw = 0;
  843. if (rune.Value == '\t') {
  844. rw += tabWidth - 1;
  845. rows += rw;
  846. } else {
  847. rw = ((Rune)rune).GetColumns ();
  848. if (rw == 0) {
  849. rows--;
  850. } else if (cw < rw) {
  851. cw = rw;
  852. vw++;
  853. }
  854. }
  855. }
  856. }
  857. if (rows > vh) {
  858. vh = rows;
  859. }
  860. w = vw;
  861. h = vh;
  862. }
  863. return new Rect (x, y, w, h);
  864. }
  865. /// <summary>
  866. /// Finds the HotKey and its location in text.
  867. /// </summary>
  868. /// <param name="text">The text to look in.</param>
  869. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  870. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the HotKey will be enabled.
  871. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  872. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  873. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  874. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  875. public static bool FindHotKey (string text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  876. {
  877. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  878. hotPos = -1;
  879. hotKey = KeyCode.Null;
  880. return false;
  881. }
  882. Rune hot_key = (Rune)0;
  883. int hot_pos = -1;
  884. // Use first hot_key char passed into 'hotKey'.
  885. // TODO: Ignore hot_key of two are provided
  886. // TODO: Do not support non-alphanumeric chars that can't be typed
  887. int i = 0;
  888. foreach (Rune c in text.EnumerateRunes ()) {
  889. if ((char)c.Value != 0xFFFD) {
  890. if (c == hotKeySpecifier) {
  891. hot_pos = i;
  892. } else if (hot_pos > -1) {
  893. hot_key = c;
  894. break;
  895. }
  896. }
  897. i++;
  898. }
  899. // Legacy support - use first upper case char if the specifier was not found
  900. if (hot_pos == -1 && firstUpperCase) {
  901. i = 0;
  902. foreach (Rune c in text.EnumerateRunes ()) {
  903. if ((char)c.Value != 0xFFFD) {
  904. if (Rune.IsUpper (c)) {
  905. hot_key = c;
  906. hot_pos = i;
  907. break;
  908. }
  909. }
  910. i++;
  911. }
  912. }
  913. if (hot_key != (Rune)0 && hot_pos != -1) {
  914. hotPos = hot_pos;
  915. var newHotKey = (KeyCode)hot_key.Value;
  916. if (newHotKey != KeyCode.Unknown && newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (hot_key))) {
  917. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z) {
  918. newHotKey &= ~KeyCode.Space;
  919. }
  920. hotKey = newHotKey;
  921. return true;
  922. }
  923. }
  924. hotPos = -1;
  925. hotKey = KeyCode.Null;
  926. return false;
  927. }
  928. /// <summary>
  929. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  930. /// it as the hotkey.
  931. /// </summary>
  932. /// <param name="text">The text to tag the hotkey in.</param>
  933. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  934. /// <returns>The text with the hotkey tagged.</returns>
  935. /// <remarks>
  936. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  937. /// </remarks>
  938. public string ReplaceHotKeyWithTag (string text, int hotPos)
  939. {
  940. // Set the high bit
  941. var runes = text.ToRuneList ();
  942. if (Rune.IsLetterOrDigit (runes [hotPos])) {
  943. runes [hotPos] = new Rune ((uint)runes [hotPos].Value);
  944. }
  945. return StringExtensions.ToString (runes);
  946. }
  947. /// <summary>
  948. /// Removes the hotkey specifier from text.
  949. /// </summary>
  950. /// <param name="text">The text to manipulate.</param>
  951. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  952. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  953. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  954. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  955. {
  956. if (string.IsNullOrEmpty (text)) {
  957. return text;
  958. }
  959. // Scan
  960. string start = string.Empty;
  961. int i = 0;
  962. foreach (Rune c in text) {
  963. if (c == hotKeySpecifier && i == hotPos) {
  964. i++;
  965. continue;
  966. }
  967. start += c;
  968. i++;
  969. }
  970. return start;
  971. }
  972. #endregion // Static Members
  973. List<string> _lines = new List<string> ();
  974. string _text = null;
  975. TextAlignment _textAlignment;
  976. VerticalTextAlignment _textVerticalAlignment;
  977. TextDirection _textDirection;
  978. Key _hotKey = new Key ();
  979. int _hotKeyPos = -1;
  980. Size _size;
  981. private bool _autoSize;
  982. private bool _preserveTrailingSpaces;
  983. private int _tabWidth = 4;
  984. private bool _wordWrap = true;
  985. private bool _multiLine;
  986. /// <summary>
  987. /// Event invoked when the <see cref="HotKey"/> is changed.
  988. /// </summary>
  989. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  990. /// <summary>
  991. /// The text to be displayed. This string is never modified.
  992. /// </summary>
  993. public virtual string Text {
  994. get => _text;
  995. set {
  996. var textWasNull = _text == null && value != null;
  997. _text = EnableNeedsFormat (value);
  998. if ((AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) || (textWasNull && Size.IsEmpty)) {
  999. Size = CalcRect (0, 0, _text, _textDirection, TabWidth).Size;
  1000. }
  1001. //if (_text != null && _text.GetRuneCount () > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != _text.GetColumns ())) {
  1002. // // Provide a default size (width = length of longest line, height = 1)
  1003. // // TODO: It might makes more sense for the default to be width = length of first line?
  1004. // Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  1005. //}
  1006. }
  1007. }
  1008. /// <summary>
  1009. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  1010. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  1011. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  1012. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  1013. /// </summary>
  1014. /// <remarks>
  1015. /// Auto size is ignored if the <see cref="TextAlignment.Justified"/> and <see cref="VerticalTextAlignment.Justified"/> are used.
  1016. /// </remarks>
  1017. public bool AutoSize {
  1018. get => _autoSize;
  1019. set {
  1020. _autoSize = EnableNeedsFormat (value);
  1021. if (_autoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1022. Size = CalcRect (0, 0, Text, _textDirection, TabWidth).Size;
  1023. }
  1024. }
  1025. }
  1026. /// <summary>
  1027. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved
  1028. /// or not when <see cref="TextFormatter.WordWrap"/> is enabled.
  1029. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be removed when
  1030. /// <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  1031. /// </summary>
  1032. public bool PreserveTrailingSpaces {
  1033. get => _preserveTrailingSpaces;
  1034. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  1035. }
  1036. /// <summary>
  1037. /// Controls the horizontal text-alignment property.
  1038. /// </summary>
  1039. /// <value>The text alignment.</value>
  1040. public TextAlignment Alignment {
  1041. get => _textAlignment;
  1042. set => _textAlignment = EnableNeedsFormat (value);
  1043. }
  1044. /// <summary>
  1045. /// Controls the vertical text-alignment property.
  1046. /// </summary>
  1047. /// <value>The text vertical alignment.</value>
  1048. public VerticalTextAlignment VerticalAlignment {
  1049. get => _textVerticalAlignment;
  1050. set => _textVerticalAlignment = EnableNeedsFormat (value);
  1051. }
  1052. /// <summary>
  1053. /// Controls the text-direction property.
  1054. /// </summary>
  1055. /// <value>The text vertical alignment.</value>
  1056. public TextDirection Direction {
  1057. get => _textDirection;
  1058. set => _textDirection = EnableNeedsFormat (value);
  1059. }
  1060. /// <summary>
  1061. /// Check if it is a horizontal direction
  1062. /// </summary>
  1063. public static bool IsHorizontalDirection (TextDirection textDirection)
  1064. {
  1065. switch (textDirection) {
  1066. case TextDirection.LeftRight_TopBottom:
  1067. case TextDirection.LeftRight_BottomTop:
  1068. case TextDirection.RightLeft_TopBottom:
  1069. case TextDirection.RightLeft_BottomTop:
  1070. return true;
  1071. default:
  1072. return false;
  1073. }
  1074. }
  1075. /// <summary>
  1076. /// Check if it is a vertical direction
  1077. /// </summary>
  1078. public static bool IsVerticalDirection (TextDirection textDirection)
  1079. {
  1080. switch (textDirection) {
  1081. case TextDirection.TopBottom_LeftRight:
  1082. case TextDirection.TopBottom_RightLeft:
  1083. case TextDirection.BottomTop_LeftRight:
  1084. case TextDirection.BottomTop_RightLeft:
  1085. return true;
  1086. default:
  1087. return false;
  1088. }
  1089. }
  1090. /// <summary>
  1091. /// Check if it is Left to Right direction
  1092. /// </summary>
  1093. public static bool IsLeftToRight (TextDirection textDirection)
  1094. {
  1095. switch (textDirection) {
  1096. case TextDirection.LeftRight_TopBottom:
  1097. case TextDirection.LeftRight_BottomTop:
  1098. return true;
  1099. default:
  1100. return false;
  1101. }
  1102. }
  1103. /// <summary>
  1104. /// Check if it is Top to Bottom direction
  1105. /// </summary>
  1106. public static bool IsTopToBottom (TextDirection textDirection)
  1107. {
  1108. switch (textDirection) {
  1109. case TextDirection.TopBottom_LeftRight:
  1110. case TextDirection.TopBottom_RightLeft:
  1111. return true;
  1112. default:
  1113. return false;
  1114. }
  1115. }
  1116. /// <summary>
  1117. /// Allows word wrap the to fit the available container width.
  1118. /// </summary>
  1119. public bool WordWrap {
  1120. get => _wordWrap;
  1121. set => _wordWrap = EnableNeedsFormat (value);
  1122. }
  1123. /// <summary>
  1124. /// Gets or sets the size of the area the text will be constrained to when formatted.
  1125. /// </summary>
  1126. /// <remarks>
  1127. /// Does not return the size the formatted text; just the value that was set.
  1128. /// </remarks>
  1129. public Size Size {
  1130. get => _size;
  1131. set {
  1132. if (AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1133. _size = EnableNeedsFormat (CalcRect (0, 0, Text, _textDirection, TabWidth).Size);
  1134. } else {
  1135. _size = EnableNeedsFormat (value);
  1136. }
  1137. }
  1138. }
  1139. /// <summary>
  1140. /// The specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable hot key support for this View instance. The default is '\xffff'.
  1141. /// </summary>
  1142. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  1143. /// <summary>
  1144. /// The position in the text of the hot key. The hot key will be rendered using the hot color.
  1145. /// </summary>
  1146. public int HotKeyPos { get => _hotKeyPos; internal set => _hotKeyPos = value; }
  1147. /// <summary>
  1148. /// Gets or sets the hot key. Must be be an upper case letter or digit. Fires the <see cref="HotKeyChanged"/> event.
  1149. /// </summary>
  1150. public Key HotKey {
  1151. get => _hotKey;
  1152. internal set {
  1153. if (_hotKey != value) {
  1154. var oldKey = _hotKey;
  1155. _hotKey = value;
  1156. HotKeyChanged?.Invoke (this, new KeyChangedEventArgs (oldKey, value));
  1157. }
  1158. }
  1159. }
  1160. /// <summary>
  1161. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  1162. /// </summary>
  1163. public int CursorPosition { get; internal set; }
  1164. /// <summary>
  1165. /// Gets the size required to hold the formatted text, given the constraints placed by <see cref="Size"/>.
  1166. /// </summary>
  1167. /// <remarks>
  1168. /// Causes a format, resetting <see cref="NeedsFormat"/>.
  1169. /// </remarks>
  1170. /// <returns></returns>
  1171. public Size GetFormattedSize ()
  1172. {
  1173. var lines = Lines;
  1174. var width = Lines.Max (line => line.GetColumns ());
  1175. var height = Lines.Count;
  1176. return new Size (width, height);
  1177. }
  1178. /// <summary>
  1179. /// Gets the formatted lines.
  1180. /// </summary>
  1181. /// <remarks>
  1182. /// <para>
  1183. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  1184. /// <see cref="Format(string, int, bool, bool, bool, int, TextDirection, bool)"/> will be called internally.
  1185. /// </para>
  1186. /// </remarks>
  1187. public List<string> Lines {
  1188. get {
  1189. // With this check, we protect against subclasses with overrides of Text
  1190. if (string.IsNullOrEmpty (Text) || Size.IsEmpty) {
  1191. _lines = new List<string> {
  1192. string.Empty
  1193. };
  1194. NeedsFormat = false;
  1195. return _lines;
  1196. }
  1197. if (NeedsFormat) {
  1198. var shown_text = _text;
  1199. if (FindHotKey (_text, HotKeySpecifier, true, out _hotKeyPos, out var newHotKey)) {
  1200. HotKey = newHotKey;
  1201. shown_text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  1202. shown_text = ReplaceHotKeyWithTag (shown_text, _hotKeyPos);
  1203. }
  1204. if (IsVerticalDirection (_textDirection)) {
  1205. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1, TabWidth);
  1206. _lines = Format (shown_text, Size.Height, VerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth && WordWrap,
  1207. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1208. if (!AutoSize) {
  1209. colsWidth = GetMaxColsForWidth (_lines, Size.Width, TabWidth);
  1210. if (_lines.Count > colsWidth) {
  1211. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  1212. }
  1213. }
  1214. } else {
  1215. _lines = Format (shown_text, Size.Width, Alignment == TextAlignment.Justified, Size.Height > 1 && WordWrap,
  1216. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1217. if (!AutoSize && _lines.Count > Size.Height) {
  1218. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  1219. }
  1220. }
  1221. NeedsFormat = false;
  1222. }
  1223. return _lines;
  1224. }
  1225. }
  1226. /// <summary>
  1227. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect, bool, ConsoleDriver)"/> is called.
  1228. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  1229. /// </summary>
  1230. /// <remarks>
  1231. /// <para>
  1232. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  1233. /// </para>
  1234. /// </remarks>
  1235. public bool NeedsFormat { get; set; }
  1236. /// <summary>
  1237. /// Gets or sets the number of columns used for a tab.
  1238. /// </summary>
  1239. public int TabWidth {
  1240. get => _tabWidth;
  1241. set => _tabWidth = EnableNeedsFormat (value);
  1242. }
  1243. /// <summary>
  1244. /// Gets or sets a value indicating whether multi line is allowed.
  1245. /// </summary>
  1246. /// <remarks>
  1247. /// Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.
  1248. /// </remarks>
  1249. public bool MultiLine {
  1250. get => _multiLine;
  1251. set {
  1252. _multiLine = EnableNeedsFormat (value);
  1253. }
  1254. }
  1255. private T EnableNeedsFormat<T> (T value)
  1256. {
  1257. NeedsFormat = true;
  1258. return value;
  1259. }
  1260. /// <summary>
  1261. /// Causes the <see cref="TextFormatter"/> to reformat the text.
  1262. /// </summary>
  1263. /// <returns>The formatted text.</returns>
  1264. public string Format ()
  1265. {
  1266. var sb = new StringBuilder ();
  1267. // Lines_get causes a Format
  1268. foreach (var line in Lines) {
  1269. sb.AppendLine (line);
  1270. }
  1271. return sb.ToString ();
  1272. }
  1273. /// <summary>
  1274. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="ConsoleDriver"/> using the colors specified.
  1275. /// </summary>
  1276. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1277. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1278. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1279. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1280. /// <param name="fillRemaining">Determines if the bounds width will be used (default) or only the text width will be used.</param>
  1281. /// <param name="driver">The console driver currently used by the application.</param>
  1282. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default, bool fillRemaining = true, ConsoleDriver driver = null)
  1283. {
  1284. // With this check, we protect against subclasses with overrides of Text (like Button)
  1285. if (string.IsNullOrEmpty (_text)) {
  1286. return;
  1287. }
  1288. if (driver == null) {
  1289. driver = Application.Driver;
  1290. }
  1291. driver?.SetAttribute (normalColor);
  1292. // Use "Lines" to ensure a Format (don't use "lines"))
  1293. var linesFormated = Lines;
  1294. switch (_textDirection) {
  1295. case TextDirection.TopBottom_RightLeft:
  1296. case TextDirection.LeftRight_BottomTop:
  1297. case TextDirection.RightLeft_BottomTop:
  1298. case TextDirection.BottomTop_RightLeft:
  1299. linesFormated.Reverse ();
  1300. break;
  1301. }
  1302. var isVertical = IsVerticalDirection (_textDirection);
  1303. var maxBounds = bounds;
  1304. if (driver != null) {
  1305. maxBounds = containerBounds == default
  1306. ? bounds
  1307. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1308. Math.Max (containerBounds.Y, bounds.Y),
  1309. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1310. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1311. }
  1312. if (maxBounds.Width == 0 || maxBounds.Height == 0) {
  1313. return;
  1314. }
  1315. // BUGBUG: v2 - TextFormatter should not change the clip region. If a caller wants to break out of the clip region it should do
  1316. // so explicitly.
  1317. //var savedClip = Application.Driver?.Clip;
  1318. //if (Application.Driver != null) {
  1319. // Application.Driver.Clip = maxBounds;
  1320. //}
  1321. var lineOffset = !isVertical && bounds.Y < 0 ? Math.Abs (bounds.Y) : 0;
  1322. for (int line = lineOffset; line < linesFormated.Count; line++) {
  1323. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1324. continue;
  1325. if ((isVertical && line >= maxBounds.Left + maxBounds.Width)
  1326. || (!isVertical && line >= maxBounds.Top + maxBounds.Height + lineOffset))
  1327. break;
  1328. var runes = _lines [line].ToRunes ();
  1329. switch (_textDirection) {
  1330. case TextDirection.RightLeft_BottomTop:
  1331. case TextDirection.RightLeft_TopBottom:
  1332. case TextDirection.BottomTop_LeftRight:
  1333. case TextDirection.BottomTop_RightLeft:
  1334. runes = runes.Reverse ().ToArray ();
  1335. break;
  1336. }
  1337. // When text is justified, we lost left or right, so we use the direction to align.
  1338. int x, y;
  1339. // Horizontal Alignment
  1340. if (_textAlignment == TextAlignment.Right || (_textAlignment == TextAlignment.Justified && !IsLeftToRight (_textDirection))) {
  1341. if (isVertical) {
  1342. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1343. x = bounds.Right - runesWidth;
  1344. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1345. } else {
  1346. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1347. x = bounds.Right - runesWidth;
  1348. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1349. }
  1350. } else if (_textAlignment == TextAlignment.Left || _textAlignment == TextAlignment.Justified) {
  1351. if (isVertical) {
  1352. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line, TabWidth) : 0;
  1353. x = bounds.Left + runesWidth;
  1354. } else {
  1355. x = bounds.Left;
  1356. }
  1357. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  1358. } else if (_textAlignment == TextAlignment.Centered) {
  1359. if (isVertical) {
  1360. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1361. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1362. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1363. } else {
  1364. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1365. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1366. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1367. }
  1368. } else {
  1369. throw new ArgumentOutOfRangeException ();
  1370. }
  1371. // Vertical Alignment
  1372. if (_textVerticalAlignment == VerticalTextAlignment.Bottom || (_textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (_textDirection))) {
  1373. if (isVertical) {
  1374. y = bounds.Bottom - runes.Length;
  1375. } else {
  1376. y = bounds.Bottom - Lines.Count + line;
  1377. }
  1378. } else if (_textVerticalAlignment == VerticalTextAlignment.Top || _textVerticalAlignment == VerticalTextAlignment.Justified) {
  1379. if (isVertical) {
  1380. y = bounds.Top;
  1381. } else {
  1382. y = bounds.Top + line;
  1383. }
  1384. } else if (_textVerticalAlignment == VerticalTextAlignment.Middle) {
  1385. if (isVertical) {
  1386. var s = (bounds.Height - runes.Length) / 2;
  1387. y = bounds.Top + s;
  1388. } else {
  1389. var s = (bounds.Height - Lines.Count) / 2;
  1390. y = bounds.Top + line + s;
  1391. }
  1392. } else {
  1393. throw new ArgumentOutOfRangeException ();
  1394. }
  1395. var colOffset = bounds.X < 0 ? Math.Abs (bounds.X) : 0;
  1396. var start = isVertical ? bounds.Top : bounds.Left;
  1397. var size = isVertical ? bounds.Height : bounds.Width;
  1398. var current = start + colOffset;
  1399. List<Point?> lastZeroWidthPos = null;
  1400. Rune rune = default;
  1401. Rune lastRuneUsed;
  1402. var zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  1403. for (var idx = (isVertical ? start - y : start - x) + colOffset; current < start + size + zeroLengthCount; idx++) {
  1404. lastRuneUsed = rune;
  1405. if (lastZeroWidthPos == null) {
  1406. if (idx < 0 || x + current + colOffset < 0) {
  1407. current++;
  1408. continue;
  1409. } else if (!fillRemaining && idx > runes.Length - 1) {
  1410. break;
  1411. }
  1412. if ((!isVertical && current - start > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1413. || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y)) {
  1414. break;
  1415. }
  1416. }
  1417. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1418. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y))
  1419. // break;
  1420. rune = (Rune)' ';
  1421. if (isVertical) {
  1422. if (idx >= 0 && idx < runes.Length) {
  1423. rune = runes [idx];
  1424. }
  1425. if (lastZeroWidthPos == null) {
  1426. driver?.Move (x, current);
  1427. } else {
  1428. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1429. if (foundIdx > -1) {
  1430. if (rune.IsCombiningMark ()) {
  1431. lastZeroWidthPos [foundIdx] = (new Point (lastZeroWidthPos [foundIdx].Value.X + 1, current));
  1432. driver?.Move (lastZeroWidthPos [foundIdx].Value.X, current);
  1433. } else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ()) {
  1434. current++;
  1435. driver?.Move (x, current);
  1436. } else {
  1437. driver?.Move (x, current);
  1438. }
  1439. } else {
  1440. driver?.Move (x, current);
  1441. }
  1442. }
  1443. } else {
  1444. driver?.Move (current, y);
  1445. if (idx >= 0 && idx < runes.Length) {
  1446. rune = runes [idx];
  1447. }
  1448. }
  1449. var runeWidth = GetRuneWidth (rune, TabWidth);
  1450. if (HotKeyPos > -1 && idx == HotKeyPos) {
  1451. if ((isVertical && _textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1452. (!isVertical && _textAlignment == TextAlignment.Justified)) {
  1453. CursorPosition = idx - start;
  1454. }
  1455. driver?.SetAttribute (hotColor);
  1456. driver?.AddRune (rune);
  1457. driver?.SetAttribute (normalColor);
  1458. } else {
  1459. if (isVertical) {
  1460. if (runeWidth == 0) {
  1461. if (lastZeroWidthPos == null) {
  1462. lastZeroWidthPos = new List<Point?> ();
  1463. }
  1464. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1465. if (foundIdx == -1) {
  1466. current--;
  1467. lastZeroWidthPos.Add ((new Point (x + 1, current)));
  1468. }
  1469. driver?.Move (x + 1, current);
  1470. }
  1471. }
  1472. driver?.AddRune (rune);
  1473. }
  1474. if (isVertical) {
  1475. if (runeWidth > 0) {
  1476. current++;
  1477. }
  1478. } else {
  1479. current += runeWidth;
  1480. }
  1481. var nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length ? runes [idx + 1].GetColumns () : 0;
  1482. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size) {
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. //if (Application.Driver != null) {
  1488. // Application.Driver.Clip = (Rect)savedClip;
  1489. //}
  1490. }
  1491. }
  1492. }