TextFormatter.cs 54 KB

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