TextFormatter.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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="hotPos">Outputs the Rune index into <c>text</c>.</param>
  898. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  899. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the
  900. /// first upper case character as the HotKey will be enabled.
  901. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  902. /// Defaults to <see langword="false"/>.</param>
  903. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  904. public static bool FindHotKey (string text, Rune hotKeySpecifier, out int hotPos, out Key hotKey, bool firstUpperCase = false)
  905. {
  906. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  907. hotPos = -1;
  908. hotKey = KeyCode.Null;
  909. return false;
  910. }
  911. Rune hot_key = (Rune)0;
  912. int hot_pos = -1;
  913. // Use first hot_key char passed into 'hotKey'.
  914. // TODO: Ignore hot_key of two are provided
  915. // TODO: Do not support non-alphanumeric chars that can't be typed
  916. int i = 0;
  917. foreach (Rune c in text.EnumerateRunes ()) {
  918. if ((char)c.Value != 0xFFFD) {
  919. if (c == hotKeySpecifier) {
  920. hot_pos = i;
  921. } else if (hot_pos > -1) {
  922. hot_key = c;
  923. break;
  924. }
  925. }
  926. i++;
  927. }
  928. // Legacy support - use first upper case char if the specifier was not found
  929. if (hot_pos == -1 && firstUpperCase) {
  930. i = 0;
  931. foreach (Rune c in text.EnumerateRunes ()) {
  932. if ((char)c.Value != 0xFFFD) {
  933. if (Rune.IsUpper (c)) {
  934. hot_key = c;
  935. hot_pos = i;
  936. break;
  937. }
  938. }
  939. i++;
  940. }
  941. }
  942. if (hot_key != (Rune)0 && hot_pos != -1) {
  943. hotPos = hot_pos;
  944. var newHotKey = (KeyCode)hot_key.Value;
  945. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (hot_key))) {
  946. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z) {
  947. newHotKey &= ~KeyCode.Space;
  948. }
  949. hotKey = newHotKey;
  950. return true;
  951. }
  952. }
  953. hotPos = -1;
  954. hotKey = KeyCode.Null;
  955. return false;
  956. }
  957. /// <summary>
  958. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  959. /// it as the hotkey.
  960. /// </summary>
  961. /// <param name="text">The text to tag the hotkey in.</param>
  962. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  963. /// <returns>The text with the hotkey tagged.</returns>
  964. /// <remarks>
  965. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  966. /// </remarks>
  967. public string ReplaceHotKeyWithTag (string text, int hotPos)
  968. {
  969. // Set the high bit
  970. var runes = text.ToRuneList ();
  971. if (Rune.IsLetterOrDigit (runes [hotPos])) {
  972. runes [hotPos] = new Rune ((uint)runes [hotPos].Value);
  973. }
  974. return StringExtensions.ToString (runes);
  975. }
  976. /// <summary>
  977. /// Removes the hotkey specifier from text.
  978. /// </summary>
  979. /// <param name="text">The text to manipulate.</param>
  980. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  981. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  982. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  983. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  984. {
  985. if (string.IsNullOrEmpty (text)) {
  986. return text;
  987. }
  988. // Scan
  989. string start = string.Empty;
  990. int i = 0;
  991. foreach (Rune c in text) {
  992. if (c == hotKeySpecifier && i == hotPos) {
  993. i++;
  994. continue;
  995. }
  996. start += c;
  997. i++;
  998. }
  999. return start;
  1000. }
  1001. #endregion // Static Members
  1002. List<string> _lines = new List<string> ();
  1003. string _text = null;
  1004. TextAlignment _textAlignment;
  1005. VerticalTextAlignment _textVerticalAlignment;
  1006. TextDirection _textDirection;
  1007. Key _hotKey = new Key ();
  1008. int _hotKeyPos = -1;
  1009. Size _size;
  1010. private bool _autoSize;
  1011. private bool _preserveTrailingSpaces;
  1012. private int _tabWidth = 4;
  1013. private bool _wordWrap = true;
  1014. private bool _multiLine;
  1015. /// <summary>
  1016. /// Event invoked when the <see cref="HotKey"/> is changed.
  1017. /// </summary>
  1018. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  1019. /// <summary>
  1020. /// The text to be displayed. This string is never modified.
  1021. /// </summary>
  1022. public virtual string Text {
  1023. get => _text;
  1024. set {
  1025. var textWasNull = _text == null && value != null;
  1026. _text = EnableNeedsFormat (value);
  1027. if ((AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) || (textWasNull && Size.IsEmpty)) {
  1028. Size = CalcRect (0, 0, _text, Direction, TabWidth).Size;
  1029. }
  1030. //if (_text != null && _text.GetRuneCount () > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != _text.GetColumns ())) {
  1031. // // Provide a default size (width = length of longest line, height = 1)
  1032. // // TODO: It might makes more sense for the default to be width = length of first line?
  1033. // Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  1034. //}
  1035. }
  1036. }
  1037. /// <summary>
  1038. /// Gets or sets whether the <see cref="Size"/> should be automatically changed to fit the <see cref="Text"/>.
  1039. /// </summary>
  1040. /// <remarks>
  1041. /// <para>
  1042. /// Used by <see cref="View.AutoSize"/> to resize the view's <see cref="View.Bounds"/> to fit <see cref="Size"/>.
  1043. /// </para>
  1044. /// <para>
  1045. /// AutoSize is ignored if <see cref="TextAlignment.Justified"/> and <see cref="VerticalTextAlignment.Justified"/> are used.
  1046. /// </para>
  1047. /// </remarks>
  1048. public bool AutoSize {
  1049. get => _autoSize;
  1050. set {
  1051. _autoSize = EnableNeedsFormat (value);
  1052. if (_autoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1053. Size = CalcRect (0, 0, _text, Direction, TabWidth).Size;
  1054. }
  1055. }
  1056. }
  1057. /// <summary>
  1058. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved
  1059. /// or not when <see cref="TextFormatter.WordWrap"/> is enabled.
  1060. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be removed when
  1061. /// <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  1062. /// </summary>
  1063. public bool PreserveTrailingSpaces {
  1064. get => _preserveTrailingSpaces;
  1065. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  1066. }
  1067. /// <summary>
  1068. /// Controls the horizontal text-alignment property.
  1069. /// </summary>
  1070. /// <value>The text alignment.</value>
  1071. public TextAlignment Alignment {
  1072. get => _textAlignment;
  1073. set => _textAlignment = EnableNeedsFormat (value);
  1074. }
  1075. /// <summary>
  1076. /// Controls the vertical text-alignment property.
  1077. /// </summary>
  1078. /// <value>The text vertical alignment.</value>
  1079. public VerticalTextAlignment VerticalAlignment {
  1080. get => _textVerticalAlignment;
  1081. set => _textVerticalAlignment = EnableNeedsFormat (value);
  1082. }
  1083. /// <summary>
  1084. /// Controls the text-direction property.
  1085. /// </summary>
  1086. /// <value>The text vertical alignment.</value>
  1087. public TextDirection Direction {
  1088. get => _textDirection;
  1089. set {
  1090. _textDirection = EnableNeedsFormat (value);
  1091. if (AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1092. Size = CalcRect (0, 0, Text, Direction, TabWidth).Size;
  1093. }
  1094. }
  1095. }
  1096. /// <summary>
  1097. /// Check if it is a horizontal direction
  1098. /// </summary>
  1099. public static bool IsHorizontalDirection (TextDirection textDirection)
  1100. {
  1101. switch (textDirection) {
  1102. case TextDirection.LeftRight_TopBottom:
  1103. case TextDirection.LeftRight_BottomTop:
  1104. case TextDirection.RightLeft_TopBottom:
  1105. case TextDirection.RightLeft_BottomTop:
  1106. return true;
  1107. default:
  1108. return false;
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// Check if it is a vertical direction
  1113. /// </summary>
  1114. public static bool IsVerticalDirection (TextDirection textDirection)
  1115. {
  1116. switch (textDirection) {
  1117. case TextDirection.TopBottom_LeftRight:
  1118. case TextDirection.TopBottom_RightLeft:
  1119. case TextDirection.BottomTop_LeftRight:
  1120. case TextDirection.BottomTop_RightLeft:
  1121. return true;
  1122. default:
  1123. return false;
  1124. }
  1125. }
  1126. /// <summary>
  1127. /// Check if it is Left to Right direction
  1128. /// </summary>
  1129. public static bool IsLeftToRight (TextDirection textDirection)
  1130. {
  1131. switch (textDirection) {
  1132. case TextDirection.LeftRight_TopBottom:
  1133. case TextDirection.LeftRight_BottomTop:
  1134. return true;
  1135. default:
  1136. return false;
  1137. }
  1138. }
  1139. /// <summary>
  1140. /// Check if it is Top to Bottom direction
  1141. /// </summary>
  1142. public static bool IsTopToBottom (TextDirection textDirection)
  1143. {
  1144. switch (textDirection) {
  1145. case TextDirection.TopBottom_LeftRight:
  1146. case TextDirection.TopBottom_RightLeft:
  1147. return true;
  1148. default:
  1149. return false;
  1150. }
  1151. }
  1152. /// <summary>
  1153. /// Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="Size"/>.
  1154. /// </summary>
  1155. public bool WordWrap {
  1156. get => _wordWrap;
  1157. set => _wordWrap = EnableNeedsFormat (value);
  1158. }
  1159. /// <summary>
  1160. /// Gets or sets the size <see cref="Text"/> will be constrained to when formatted.
  1161. /// </summary>
  1162. /// <remarks>
  1163. /// Does not return the size of the formatted text but the size that will be used to constrain the text when formatted.
  1164. /// </remarks>
  1165. public Size Size {
  1166. get => _size;
  1167. set {
  1168. if (AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) {
  1169. _size = EnableNeedsFormat (CalcRect (0, 0, Text, Direction, TabWidth).Size);
  1170. } else {
  1171. _size = EnableNeedsFormat (value);
  1172. }
  1173. }
  1174. }
  1175. /// <summary>
  1176. /// 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'.
  1177. /// </summary>
  1178. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  1179. /// <summary>
  1180. /// The position in the text of the hot key. The hot key will be rendered using the hot color.
  1181. /// </summary>
  1182. public int HotKeyPos { get => _hotKeyPos; internal set => _hotKeyPos = value; }
  1183. /// <summary>
  1184. /// Gets or sets the hot key. Must be be an upper case letter or digit. Fires the <see cref="HotKeyChanged"/> event.
  1185. /// </summary>
  1186. public Key HotKey {
  1187. get => _hotKey;
  1188. internal set {
  1189. if (_hotKey != value) {
  1190. var oldKey = _hotKey;
  1191. _hotKey = value;
  1192. HotKeyChanged?.Invoke (this, new KeyChangedEventArgs (oldKey, value));
  1193. }
  1194. }
  1195. }
  1196. /// <summary>
  1197. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  1198. /// </summary>
  1199. public int CursorPosition { get; internal set; }
  1200. /// <summary>
  1201. /// Gets the size required to hold the formatted text, given the constraints placed by <see cref="Size"/>.
  1202. /// </summary>
  1203. /// <remarks>
  1204. /// Causes a format, resetting <see cref="NeedsFormat"/>.
  1205. /// </remarks>
  1206. /// <returns></returns>
  1207. public Size GetFormattedSize ()
  1208. {
  1209. var lines = Lines;
  1210. var width = Lines.Max (line => line.GetColumns ());
  1211. var height = Lines.Count;
  1212. return new Size (width, height);
  1213. }
  1214. /// <summary>
  1215. /// Gets the formatted lines.
  1216. /// </summary>
  1217. /// <remarks>
  1218. /// <para>
  1219. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  1220. /// <see cref="Format(string, int, bool, bool, bool, int, TextDirection, bool)"/> will be called internally.
  1221. /// </para>
  1222. /// </remarks>
  1223. public List<string> Lines {
  1224. get {
  1225. // With this check, we protect against subclasses with overrides of Text
  1226. if (string.IsNullOrEmpty (Text) || Size.IsEmpty) {
  1227. _lines = new List<string> {
  1228. string.Empty
  1229. };
  1230. NeedsFormat = false;
  1231. return _lines;
  1232. }
  1233. if (NeedsFormat) {
  1234. var shown_text = _text;
  1235. if (FindHotKey (_text, HotKeySpecifier, out _hotKeyPos, out var newHotKey)) {
  1236. HotKey = newHotKey;
  1237. shown_text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  1238. shown_text = ReplaceHotKeyWithTag (shown_text, _hotKeyPos);
  1239. }
  1240. if (IsVerticalDirection (Direction)) {
  1241. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1, TabWidth);
  1242. _lines = Format (shown_text, Size.Height, VerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth && WordWrap,
  1243. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1244. if (!AutoSize) {
  1245. colsWidth = GetMaxColsForWidth (_lines, Size.Width, TabWidth);
  1246. if (_lines.Count > colsWidth) {
  1247. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  1248. }
  1249. }
  1250. } else {
  1251. _lines = Format (shown_text, Size.Width, Alignment == TextAlignment.Justified, Size.Height > 1 && WordWrap,
  1252. PreserveTrailingSpaces, TabWidth, Direction, MultiLine);
  1253. if (!AutoSize && _lines.Count > Size.Height) {
  1254. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  1255. }
  1256. }
  1257. NeedsFormat = false;
  1258. }
  1259. return _lines;
  1260. }
  1261. }
  1262. /// <summary>
  1263. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.
  1264. /// </summary>
  1265. /// <remarks>
  1266. /// <para>
  1267. /// If <c>false</c> when Draw is called, the Draw call will be faster.
  1268. /// </para>
  1269. /// <para>
  1270. /// Used by <see cref="Draw(Rect, Attribute, Attribute, Rect, bool, ConsoleDriver)"/>
  1271. /// </para>
  1272. /// <para>
  1273. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  1274. /// </para>
  1275. /// </remarks>
  1276. public bool NeedsFormat { get; set; }
  1277. /// <summary>
  1278. /// Gets or sets the number of columns used for a tab.
  1279. /// </summary>
  1280. public int TabWidth {
  1281. get => _tabWidth;
  1282. set => _tabWidth = EnableNeedsFormat (value);
  1283. }
  1284. /// <summary>
  1285. /// Gets or sets a value indicating whether multi line is allowed.
  1286. /// </summary>
  1287. /// <remarks>
  1288. /// Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.
  1289. /// </remarks>
  1290. public bool MultiLine {
  1291. get => _multiLine;
  1292. set {
  1293. _multiLine = EnableNeedsFormat (value);
  1294. }
  1295. }
  1296. private T EnableNeedsFormat<T> (T value)
  1297. {
  1298. NeedsFormat = true;
  1299. return value;
  1300. }
  1301. /// <summary>
  1302. /// Causes the <see cref="TextFormatter"/> to reformat the text.
  1303. /// </summary>
  1304. /// <returns>The formatted text.</returns>
  1305. public string Format ()
  1306. {
  1307. var sb = new StringBuilder ();
  1308. // Lines_get causes a Format
  1309. foreach (var line in Lines) {
  1310. sb.AppendLine (line);
  1311. }
  1312. return sb.ToString ().TrimEnd (Environment.NewLine.ToCharArray ());
  1313. }
  1314. /// <summary>
  1315. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="ConsoleDriver"/> using the colors specified.
  1316. /// </summary>
  1317. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1318. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1319. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1320. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1321. /// <param name="fillRemaining">Determines if the bounds width will be used (default) or only the text width will be used.</param>
  1322. /// <param name="driver">The console driver currently used by the application.</param>
  1323. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default, bool fillRemaining = true, ConsoleDriver driver = null)
  1324. {
  1325. // With this check, we protect against subclasses with overrides of Text (like Button)
  1326. if (string.IsNullOrEmpty (_text)) {
  1327. return;
  1328. }
  1329. if (driver == null) {
  1330. driver = Application.Driver;
  1331. }
  1332. driver?.SetAttribute (normalColor);
  1333. // Use "Lines" to ensure a Format (don't use "lines"))
  1334. var linesFormated = Lines;
  1335. switch (Direction) {
  1336. case TextDirection.TopBottom_RightLeft:
  1337. case TextDirection.LeftRight_BottomTop:
  1338. case TextDirection.RightLeft_BottomTop:
  1339. case TextDirection.BottomTop_RightLeft:
  1340. linesFormated.Reverse ();
  1341. break;
  1342. }
  1343. var isVertical = IsVerticalDirection (Direction);
  1344. var maxBounds = bounds;
  1345. if (driver != null) {
  1346. maxBounds = containerBounds == default
  1347. ? bounds
  1348. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1349. Math.Max (containerBounds.Y, bounds.Y),
  1350. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1351. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1352. }
  1353. if (maxBounds.Width == 0 || maxBounds.Height == 0) {
  1354. return;
  1355. }
  1356. // BUGBUG: v2 - TextFormatter should not change the clip region. If a caller wants to break out of the clip region it should do
  1357. // so explicitly.
  1358. //var savedClip = Application.Driver?.Clip;
  1359. //if (Application.Driver != null) {
  1360. // Application.Driver.Clip = maxBounds;
  1361. //}
  1362. var lineOffset = !isVertical && bounds.Y < 0 ? Math.Abs (bounds.Y) : 0;
  1363. for (int line = lineOffset; line < linesFormated.Count; line++) {
  1364. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1365. continue;
  1366. if ((isVertical && line >= maxBounds.Left + maxBounds.Width)
  1367. || (!isVertical && line >= maxBounds.Top + maxBounds.Height + lineOffset))
  1368. break;
  1369. var runes = _lines [line].ToRunes ();
  1370. switch (Direction) {
  1371. case TextDirection.RightLeft_BottomTop:
  1372. case TextDirection.RightLeft_TopBottom:
  1373. case TextDirection.BottomTop_LeftRight:
  1374. case TextDirection.BottomTop_RightLeft:
  1375. runes = runes.Reverse ().ToArray ();
  1376. break;
  1377. }
  1378. // When text is justified, we lost left or right, so we use the direction to align.
  1379. int x, y;
  1380. // Horizontal Alignment
  1381. if (_textAlignment == TextAlignment.Right || (_textAlignment == TextAlignment.Justified && !IsLeftToRight (Direction))) {
  1382. if (isVertical) {
  1383. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1384. x = bounds.Right - runesWidth;
  1385. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1386. } else {
  1387. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1388. x = bounds.Right - runesWidth;
  1389. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1390. }
  1391. } else if (_textAlignment == TextAlignment.Left || _textAlignment == TextAlignment.Justified) {
  1392. if (isVertical) {
  1393. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line, TabWidth) : 0;
  1394. x = bounds.Left + runesWidth;
  1395. } else {
  1396. x = bounds.Left;
  1397. }
  1398. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  1399. } else if (_textAlignment == TextAlignment.Centered) {
  1400. if (isVertical) {
  1401. var runesWidth = GetSumMaxCharWidth (Lines, line, TabWidth);
  1402. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1403. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1404. } else {
  1405. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1406. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1407. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1408. }
  1409. } else {
  1410. throw new ArgumentOutOfRangeException ();
  1411. }
  1412. // Vertical Alignment
  1413. if (_textVerticalAlignment == VerticalTextAlignment.Bottom || (_textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (Direction))) {
  1414. if (isVertical) {
  1415. y = bounds.Bottom - runes.Length;
  1416. } else {
  1417. y = bounds.Bottom - Lines.Count + line;
  1418. }
  1419. } else if (_textVerticalAlignment == VerticalTextAlignment.Top || _textVerticalAlignment == VerticalTextAlignment.Justified) {
  1420. if (isVertical) {
  1421. y = bounds.Top;
  1422. } else {
  1423. y = bounds.Top + line;
  1424. }
  1425. } else if (_textVerticalAlignment == VerticalTextAlignment.Middle) {
  1426. if (isVertical) {
  1427. var s = (bounds.Height - runes.Length) / 2;
  1428. y = bounds.Top + s;
  1429. } else {
  1430. var s = (bounds.Height - Lines.Count) / 2;
  1431. y = bounds.Top + line + s;
  1432. }
  1433. } else {
  1434. throw new ArgumentOutOfRangeException ();
  1435. }
  1436. var colOffset = bounds.X < 0 ? Math.Abs (bounds.X) : 0;
  1437. var start = isVertical ? bounds.Top : bounds.Left;
  1438. var size = isVertical ? bounds.Height : bounds.Width;
  1439. var current = start + colOffset;
  1440. List<Point?> lastZeroWidthPos = null;
  1441. Rune rune = default;
  1442. Rune lastRuneUsed;
  1443. var zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  1444. for (var idx = (isVertical ? start - y : start - x) + colOffset; current < start + size + zeroLengthCount; idx++) {
  1445. lastRuneUsed = rune;
  1446. if (lastZeroWidthPos == null) {
  1447. if (idx < 0 || x + current + colOffset < 0) {
  1448. current++;
  1449. continue;
  1450. } else if (!fillRemaining && idx > runes.Length - 1) {
  1451. break;
  1452. }
  1453. if ((!isVertical && current - start > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1454. || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y)) {
  1455. break;
  1456. }
  1457. }
  1458. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1459. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y))
  1460. // break;
  1461. rune = (Rune)' ';
  1462. if (isVertical) {
  1463. if (idx >= 0 && idx < runes.Length) {
  1464. rune = runes [idx];
  1465. }
  1466. if (lastZeroWidthPos == null) {
  1467. driver?.Move (x, current);
  1468. } else {
  1469. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1470. if (foundIdx > -1) {
  1471. if (rune.IsCombiningMark ()) {
  1472. lastZeroWidthPos [foundIdx] = (new Point (lastZeroWidthPos [foundIdx].Value.X + 1, current));
  1473. driver?.Move (lastZeroWidthPos [foundIdx].Value.X, current);
  1474. } else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ()) {
  1475. current++;
  1476. driver?.Move (x, current);
  1477. } else {
  1478. driver?.Move (x, current);
  1479. }
  1480. } else {
  1481. driver?.Move (x, current);
  1482. }
  1483. }
  1484. } else {
  1485. driver?.Move (current, y);
  1486. if (idx >= 0 && idx < runes.Length) {
  1487. rune = runes [idx];
  1488. }
  1489. }
  1490. var runeWidth = GetRuneWidth (rune, TabWidth);
  1491. if (HotKeyPos > -1 && idx == HotKeyPos) {
  1492. if ((isVertical && _textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1493. (!isVertical && _textAlignment == TextAlignment.Justified)) {
  1494. CursorPosition = idx - start;
  1495. }
  1496. driver?.SetAttribute (hotColor);
  1497. driver?.AddRune (rune);
  1498. driver?.SetAttribute (normalColor);
  1499. } else {
  1500. if (isVertical) {
  1501. if (runeWidth == 0) {
  1502. if (lastZeroWidthPos == null) {
  1503. lastZeroWidthPos = new List<Point?> ();
  1504. }
  1505. var foundIdx = lastZeroWidthPos.IndexOf (p => p.Value.Y == current);
  1506. if (foundIdx == -1) {
  1507. current--;
  1508. lastZeroWidthPos.Add ((new Point (x + 1, current)));
  1509. }
  1510. driver?.Move (x + 1, current);
  1511. }
  1512. }
  1513. driver?.AddRune (rune);
  1514. }
  1515. if (isVertical) {
  1516. if (runeWidth > 0) {
  1517. current++;
  1518. }
  1519. } else {
  1520. current += runeWidth;
  1521. }
  1522. var nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length ? runes [idx + 1].GetColumns () : 0;
  1523. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size) {
  1524. break;
  1525. }
  1526. }
  1527. }
  1528. //if (Application.Driver != null) {
  1529. // Application.Driver.Clip = (Rect)savedClip;
  1530. //}
  1531. }
  1532. }
  1533. }