TextFormatter.cs 55 KB

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