TextFormatter.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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, _textDirection, 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, _textDirection, 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 => _textDirection = EnableNeedsFormat (value);
  1088. }
  1089. /// <summary>
  1090. /// Check if it is a horizontal direction
  1091. /// </summary>
  1092. public static bool IsHorizontalDirection (TextDirection textDirection)
  1093. {
  1094. switch (textDirection) {
  1095. case TextDirection.LeftRight_TopBottom:
  1096. case TextDirection.LeftRight_BottomTop:
  1097. case TextDirection.RightLeft_TopBottom:
  1098. case TextDirection.RightLeft_BottomTop:
  1099. return true;
  1100. default:
  1101. return false;
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Check if it is a vertical direction
  1106. /// </summary>
  1107. public static bool IsVerticalDirection (TextDirection textDirection)
  1108. {
  1109. switch (textDirection) {
  1110. case TextDirection.TopBottom_LeftRight:
  1111. case TextDirection.TopBottom_RightLeft:
  1112. case TextDirection.BottomTop_LeftRight:
  1113. case TextDirection.BottomTop_RightLeft:
  1114. return true;
  1115. default:
  1116. return false;
  1117. }
  1118. }
  1119. /// <summary>
  1120. /// Check if it is Left to Right direction
  1121. /// </summary>
  1122. public static bool IsLeftToRight (TextDirection textDirection)
  1123. {
  1124. switch (textDirection) {
  1125. case TextDirection.LeftRight_TopBottom:
  1126. case TextDirection.LeftRight_BottomTop:
  1127. return true;
  1128. default:
  1129. return false;
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Check if it is Top to Bottom direction
  1134. /// </summary>
  1135. public static bool IsTopToBottom (TextDirection textDirection)
  1136. {
  1137. switch (textDirection) {
  1138. case TextDirection.TopBottom_LeftRight:
  1139. case TextDirection.TopBottom_RightLeft:
  1140. return true;
  1141. default:
  1142. return false;
  1143. }
  1144. }
  1145. /// <summary>
  1146. /// Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="Size"/>.
  1147. /// </summary>
  1148. public bool WordWrap {
  1149. get => _wordWrap;
  1150. set => _wordWrap = EnableNeedsFormat (value);
  1151. }
  1152. /// <summary>
  1153. /// Gets or sets the size <see cref="Text"/> will be constrained to when formatted.
  1154. /// </summary>
  1155. /// <remarks>
  1156. /// Does not return the size of the formatted text but the size that will be used to constrain the text when formatted.
  1157. /// </remarks>
  1158. public Size Size {
  1159. get => _size;
  1160. set {
  1161. if (AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1162. _size = EnableNeedsFormat (CalcRect (0, 0, Text, _textDirection, TabWidth).Size);
  1163. } else {
  1164. _size = EnableNeedsFormat (value);
  1165. }
  1166. }
  1167. }
  1168. /// <summary>
  1169. /// 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'.
  1170. /// </summary>
  1171. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  1172. /// <summary>
  1173. /// The position in the text of the hot key. The hot key will be rendered using the hot color.
  1174. /// </summary>
  1175. public int HotKeyPos { get => _hotKeyPos; internal set => _hotKeyPos = value; }
  1176. /// <summary>
  1177. /// Gets or sets the hot key. Must be be an upper case letter or digit. Fires the <see cref="HotKeyChanged"/> event.
  1178. /// </summary>
  1179. public Key HotKey {
  1180. get => _hotKey;
  1181. internal set {
  1182. if (_hotKey != value) {
  1183. var oldKey = _hotKey;
  1184. _hotKey = value;
  1185. HotKeyChanged?.Invoke (this, new KeyChangedEventArgs (oldKey, value));
  1186. }
  1187. }
  1188. }
  1189. /// <summary>
  1190. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  1191. /// </summary>
  1192. public int CursorPosition { get; internal set; }
  1193. /// <summary>
  1194. /// Gets the size required to hold the formatted text, given the constraints placed by <see cref="Size"/>.
  1195. /// </summary>
  1196. /// <remarks>
  1197. /// Causes a format, resetting <see cref="NeedsFormat"/>.
  1198. /// </remarks>
  1199. /// <returns></returns>
  1200. public Size GetFormattedSize ()
  1201. {
  1202. var lines = Lines;
  1203. var width = Lines.Max (line => line.GetColumns ());
  1204. var height = Lines.Count;
  1205. return new Size (width, height);
  1206. }
  1207. /// <summary>
  1208. /// Gets the formatted lines.
  1209. /// </summary>
  1210. /// <remarks>
  1211. /// <para>
  1212. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  1213. /// <see cref="Format(string, int, bool, bool, bool, int, TextDirection, bool)"/> will be called internally.
  1214. /// </para>
  1215. /// </remarks>
  1216. public List<string> Lines {
  1217. get {
  1218. // With this check, we protect against subclasses with overrides of Text
  1219. if (string.IsNullOrEmpty (Text) || Size.IsEmpty) {
  1220. _lines = new List<string> {
  1221. string.Empty
  1222. };
  1223. NeedsFormat = false;
  1224. return _lines;
  1225. }
  1226. if (NeedsFormat) {
  1227. var shown_text = _text;
  1228. if (FindHotKey (_text, HotKeySpecifier, true, out _hotKeyPos, out var newHotKey)) {
  1229. HotKey = newHotKey;
  1230. shown_text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  1231. shown_text = ReplaceHotKeyWithTag (shown_text, _hotKeyPos);
  1232. }
  1233. if (IsVerticalDirection (_textDirection)) {
  1234. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1, TabWidth);
  1235. _lines = Format (shown_text, Size.Height, VerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth && WordWrap,
  1236. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1237. if (!AutoSize) {
  1238. colsWidth = GetMaxColsForWidth (_lines, Size.Width, TabWidth);
  1239. if (_lines.Count > colsWidth) {
  1240. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  1241. }
  1242. }
  1243. } else {
  1244. _lines = Format (shown_text, Size.Width, Alignment == TextAlignment.Justified, Size.Height > 1 && WordWrap,
  1245. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1246. if (!AutoSize && _lines.Count > Size.Height) {
  1247. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  1248. }
  1249. }
  1250. NeedsFormat = false;
  1251. }
  1252. return _lines;
  1253. }
  1254. }
  1255. /// <summary>
  1256. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.
  1257. /// </summary>
  1258. /// <remarks>
  1259. /// <para>
  1260. /// If <c>false</c> when Draw is called, the Draw call will be faster.
  1261. /// </para>
  1262. /// <para>
  1263. /// Used by <see cref="Draw(Rect, Attribute, Attribute, Rect, bool, ConsoleDriver)"/>
  1264. /// </para>
  1265. /// <para>
  1266. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  1267. /// </para>
  1268. /// </remarks>
  1269. public bool NeedsFormat { get; set; }
  1270. /// <summary>
  1271. /// Gets or sets the number of columns used for a tab.
  1272. /// </summary>
  1273. public int TabWidth {
  1274. get => _tabWidth;
  1275. set => _tabWidth = EnableNeedsFormat (value);
  1276. }
  1277. /// <summary>
  1278. /// Gets or sets a value indicating whether multi line is allowed.
  1279. /// </summary>
  1280. /// <remarks>
  1281. /// Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.
  1282. /// </remarks>
  1283. public bool MultiLine {
  1284. get => _multiLine;
  1285. set {
  1286. _multiLine = EnableNeedsFormat (value);
  1287. }
  1288. }
  1289. private T EnableNeedsFormat<T> (T value)
  1290. {
  1291. NeedsFormat = true;
  1292. return value;
  1293. }
  1294. /// <summary>
  1295. /// Causes the <see cref="TextFormatter"/> to reformat the text.
  1296. /// </summary>
  1297. /// <returns>The formatted text.</returns>
  1298. public string Format ()
  1299. {
  1300. var sb = new StringBuilder ();
  1301. // Lines_get causes a Format
  1302. foreach (var line in Lines) {
  1303. sb.AppendLine (line);
  1304. }
  1305. return sb.ToString ();
  1306. }
  1307. /// <summary>
  1308. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="ConsoleDriver"/> using the colors specified.
  1309. /// </summary>
  1310. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1311. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1312. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1313. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1314. /// <param name="fillRemaining">Determines if the bounds width will be used (default) or only the text width will be used.</param>
  1315. /// <param name="driver">The console driver currently used by the application.</param>
  1316. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default, bool fillRemaining = true, ConsoleDriver driver = null)
  1317. {
  1318. // With this check, we protect against subclasses with overrides of Text (like Button)
  1319. if (string.IsNullOrEmpty (_text)) {
  1320. return;
  1321. }
  1322. if (driver == null) {
  1323. driver = Application.Driver;
  1324. }
  1325. driver?.SetAttribute (normalColor);
  1326. // Use "Lines" to ensure a Format (don't use "lines"))
  1327. var linesFormated = Lines;
  1328. switch (_textDirection) {
  1329. case TextDirection.TopBottom_RightLeft:
  1330. case TextDirection.LeftRight_BottomTop:
  1331. case TextDirection.RightLeft_BottomTop:
  1332. case TextDirection.BottomTop_RightLeft:
  1333. linesFormated.Reverse ();
  1334. break;
  1335. }
  1336. var isVertical = IsVerticalDirection (_textDirection);
  1337. var maxBounds = bounds;
  1338. if (driver != null) {
  1339. maxBounds = containerBounds == default
  1340. ? bounds
  1341. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1342. Math.Max (containerBounds.Y, bounds.Y),
  1343. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1344. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1345. }
  1346. if (maxBounds.Width == 0 || maxBounds.Height == 0) {
  1347. return;
  1348. }
  1349. // BUGBUG: v2 - TextFormatter should not change the clip region. If a caller wants to break out of the clip region it should do
  1350. // so explicitly.
  1351. //var savedClip = Application.Driver?.Clip;
  1352. //if (Application.Driver != null) {
  1353. // Application.Driver.Clip = maxBounds;
  1354. //}
  1355. var lineOffset = !isVertical && bounds.Y < 0 ? Math.Abs (bounds.Y) : 0;
  1356. for (int line = lineOffset; line < linesFormated.Count; line++) {
  1357. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1358. continue;
  1359. if ((isVertical && line >= maxBounds.Left + maxBounds.Width)
  1360. || (!isVertical && line >= maxBounds.Top + maxBounds.Height + lineOffset))
  1361. break;
  1362. var runes = _lines [line].ToRunes ();
  1363. switch (_textDirection) {
  1364. case TextDirection.RightLeft_BottomTop:
  1365. case TextDirection.RightLeft_TopBottom:
  1366. case TextDirection.BottomTop_LeftRight:
  1367. case TextDirection.BottomTop_RightLeft:
  1368. runes = runes.Reverse ().ToArray ();
  1369. break;
  1370. }
  1371. // When text is justified, we lost left or right, so we use the direction to align.
  1372. int x, y;
  1373. // Horizontal Alignment
  1374. if (_textAlignment == TextAlignment.Right || (_textAlignment == TextAlignment.Justified && !IsLeftToRight (_textDirection))) {
  1375. if (isVertical) {
  1376. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1377. x = bounds.Right - runesWidth;
  1378. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1379. } else {
  1380. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1381. x = bounds.Right - runesWidth;
  1382. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1383. }
  1384. } else if (_textAlignment == TextAlignment.Left || _textAlignment == TextAlignment.Justified) {
  1385. if (isVertical) {
  1386. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line, TabWidth) : 0;
  1387. x = bounds.Left + runesWidth;
  1388. } else {
  1389. x = bounds.Left;
  1390. }
  1391. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  1392. } else if (_textAlignment == TextAlignment.Centered) {
  1393. if (isVertical) {
  1394. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1395. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1396. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1397. } else {
  1398. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1399. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1400. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1401. }
  1402. } else {
  1403. throw new ArgumentOutOfRangeException ();
  1404. }
  1405. // Vertical Alignment
  1406. if (_textVerticalAlignment == VerticalTextAlignment.Bottom || (_textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (_textDirection))) {
  1407. if (isVertical) {
  1408. y = bounds.Bottom - runes.Length;
  1409. } else {
  1410. y = bounds.Bottom - Lines.Count + line;
  1411. }
  1412. } else if (_textVerticalAlignment == VerticalTextAlignment.Top || _textVerticalAlignment == VerticalTextAlignment.Justified) {
  1413. if (isVertical) {
  1414. y = bounds.Top;
  1415. } else {
  1416. y = bounds.Top + line;
  1417. }
  1418. } else if (_textVerticalAlignment == VerticalTextAlignment.Middle) {
  1419. if (isVertical) {
  1420. var s = (bounds.Height - runes.Length) / 2;
  1421. y = bounds.Top + s;
  1422. } else {
  1423. var s = (bounds.Height - Lines.Count) / 2;
  1424. y = bounds.Top + line + s;
  1425. }
  1426. } else {
  1427. throw new ArgumentOutOfRangeException ();
  1428. }
  1429. var colOffset = bounds.X < 0 ? Math.Abs (bounds.X) : 0;
  1430. var start = isVertical ? bounds.Top : bounds.Left;
  1431. var size = isVertical ? bounds.Height : bounds.Width;
  1432. var current = start + colOffset;
  1433. List<Point?> lastZeroWidthPos = null;
  1434. Rune rune = default;
  1435. Rune lastRuneUsed;
  1436. var zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  1437. for (var idx = (isVertical ? start - y : start - x) + colOffset; current < start + size + zeroLengthCount; idx++) {
  1438. lastRuneUsed = rune;
  1439. if (lastZeroWidthPos == null) {
  1440. if (idx < 0 || x + current + colOffset < 0) {
  1441. current++;
  1442. continue;
  1443. } else if (!fillRemaining && idx > runes.Length - 1) {
  1444. break;
  1445. }
  1446. if ((!isVertical && current - start > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1447. || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y)) {
  1448. break;
  1449. }
  1450. }
  1451. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1452. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y))
  1453. // break;
  1454. rune = (Rune)' ';
  1455. if (isVertical) {
  1456. if (idx >= 0 && idx < runes.Length) {
  1457. rune = runes [idx];
  1458. }
  1459. if (lastZeroWidthPos == null) {
  1460. driver?.Move (x, current);
  1461. } else {
  1462. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1463. if (foundIdx > -1) {
  1464. if (rune.IsCombiningMark ()) {
  1465. lastZeroWidthPos [foundIdx] = (new Point (lastZeroWidthPos [foundIdx].Value.X + 1, current));
  1466. driver?.Move (lastZeroWidthPos [foundIdx].Value.X, current);
  1467. } else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ()) {
  1468. current++;
  1469. driver?.Move (x, current);
  1470. } else {
  1471. driver?.Move (x, current);
  1472. }
  1473. } else {
  1474. driver?.Move (x, current);
  1475. }
  1476. }
  1477. } else {
  1478. driver?.Move (current, y);
  1479. if (idx >= 0 && idx < runes.Length) {
  1480. rune = runes [idx];
  1481. }
  1482. }
  1483. var runeWidth = GetRuneWidth (rune, TabWidth);
  1484. if (HotKeyPos > -1 && idx == HotKeyPos) {
  1485. if ((isVertical && _textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1486. (!isVertical && _textAlignment == TextAlignment.Justified)) {
  1487. CursorPosition = idx - start;
  1488. }
  1489. driver?.SetAttribute (hotColor);
  1490. driver?.AddRune (rune);
  1491. driver?.SetAttribute (normalColor);
  1492. } else {
  1493. if (isVertical) {
  1494. if (runeWidth == 0) {
  1495. if (lastZeroWidthPos == null) {
  1496. lastZeroWidthPos = new List<Point?> ();
  1497. }
  1498. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1499. if (foundIdx == -1) {
  1500. current--;
  1501. lastZeroWidthPos.Add ((new Point (x + 1, current)));
  1502. }
  1503. driver?.Move (x + 1, current);
  1504. }
  1505. }
  1506. driver?.AddRune (rune);
  1507. }
  1508. if (isVertical) {
  1509. if (runeWidth > 0) {
  1510. current++;
  1511. }
  1512. } else {
  1513. current += runeWidth;
  1514. }
  1515. var nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length ? runes [idx + 1].GetColumns () : 0;
  1516. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size) {
  1517. break;
  1518. }
  1519. }
  1520. }
  1521. //if (Application.Driver != null) {
  1522. // Application.Driver.Clip = (Rect)savedClip;
  1523. //}
  1524. }
  1525. }
  1526. }