TextFormatter.cs 47 KB

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