TextFormatter.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using NStack;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// Text alignment enumeration, controls how text is displayed.
  9. /// </summary>
  10. public enum TextAlignment {
  11. /// <summary>
  12. /// Aligns the text to the left of the frame.
  13. /// </summary>
  14. Left,
  15. /// <summary>
  16. /// Aligns the text to the right side of the frame.
  17. /// </summary>
  18. Right,
  19. /// <summary>
  20. /// Centers the text in the frame.
  21. /// </summary>
  22. Centered,
  23. /// <summary>
  24. /// Shows the text as justified text in the frame.
  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. /// Aligns the text to the top of the frame.
  34. /// </summary>
  35. Top,
  36. /// <summary>
  37. /// Aligns the text to the bottom of the frame.
  38. /// </summary>
  39. Bottom,
  40. /// <summary>
  41. /// Centers the text verticaly in the frame.
  42. /// </summary>
  43. Middle,
  44. /// <summary>
  45. /// Shows the text as justified text in the frame.
  46. /// </summary>
  47. Justified
  48. }
  49. /// TextDirection [H] = Horizontal [V] = Vertical
  50. /// =============
  51. /// LeftRight_TopBottom [H] Normal
  52. /// TopBottom_LeftRight [V] Normal
  53. ///
  54. /// RightLeft_TopBottom [H] Invert Text
  55. /// TopBottom_RightLeft [V] Invert Lines
  56. ///
  57. /// LeftRight_BottomTop [H] Invert Lines
  58. /// BottomTop_LeftRight [V] Invert Text
  59. ///
  60. /// RightLeft_BottomTop [H] Invert Text + Invert Lines
  61. /// BottomTop_RightLeft [V] Invert Text + Invert Lines
  62. ///
  63. /// <summary>
  64. /// Text direction enumeration, controls how text is displayed.
  65. /// </summary>
  66. public enum TextDirection {
  67. /// <summary>
  68. /// Normal horizontal direction.
  69. /// <code>HELLO<br/>WORLD</code>
  70. /// </summary>
  71. LeftRight_TopBottom,
  72. /// <summary>
  73. /// Normal vertical direction.
  74. /// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
  75. /// </summary>
  76. TopBottom_LeftRight,
  77. /// <summary>
  78. /// This is a horizontal direction. <br/> RTL
  79. /// <code>OLLEH<br/>DLROW</code>
  80. /// </summary>
  81. RightLeft_TopBottom,
  82. /// <summary>
  83. /// This is a vertical direction.
  84. /// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
  85. /// </summary>
  86. TopBottom_RightLeft,
  87. /// <summary>
  88. /// This is a horizontal direction.
  89. /// <code>WORLD<br/>HELLO</code>
  90. /// </summary>
  91. LeftRight_BottomTop,
  92. /// <summary>
  93. /// This is a vertical direction.
  94. /// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
  95. /// </summary>
  96. BottomTop_LeftRight,
  97. /// <summary>
  98. /// This is a horizontal direction.
  99. /// <code>DLROW<br/>OLLEH</code>
  100. /// </summary>
  101. RightLeft_BottomTop,
  102. /// <summary>
  103. /// This is a vertical direction.
  104. /// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
  105. /// </summary>
  106. BottomTop_RightLeft
  107. }
  108. /// <summary>
  109. /// Provides text formatting capabilities for console apps. Supports, hotkeys, horizontal alignment, multiple lines, and word-based line wrap.
  110. /// </summary>
  111. public class TextFormatter {
  112. List<ustring> lines = new List<ustring> ();
  113. ustring text;
  114. TextAlignment textAlignment;
  115. VerticalTextAlignment textVerticalAlignment;
  116. TextDirection textDirection;
  117. Attribute textColor = -1;
  118. bool needsFormat;
  119. Key hotKey;
  120. Size size;
  121. /// <summary>
  122. /// The text to be displayed. This text is never modified.
  123. /// </summary>
  124. public virtual ustring Text {
  125. get => text;
  126. set {
  127. text = value;
  128. if (text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.RuneCount)) {
  129. // Provide a default size (width = length of longest line, height = 1)
  130. // TODO: It might makes more sense for the default to be width = length of first line?
  131. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  132. }
  133. NeedsFormat = true;
  134. }
  135. }
  136. /// <summary>
  137. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  138. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  139. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  140. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  141. /// </summary>
  142. public bool AutoSize { get; set; }
  143. // TODO: Add Vertical Text Alignment
  144. /// <summary>
  145. /// Controls the horizontal text-alignment property.
  146. /// </summary>
  147. /// <value>The text alignment.</value>
  148. public TextAlignment Alignment {
  149. get => textAlignment;
  150. set {
  151. textAlignment = value;
  152. NeedsFormat = true;
  153. }
  154. }
  155. /// <summary>
  156. /// Controls the vertical text-alignment property.
  157. /// </summary>
  158. /// <value>The text vertical alignment.</value>
  159. public VerticalTextAlignment VerticalAlignment {
  160. get => textVerticalAlignment;
  161. set {
  162. textVerticalAlignment = value;
  163. NeedsFormat = true;
  164. }
  165. }
  166. /// <summary>
  167. /// Controls the text-direction property.
  168. /// </summary>
  169. /// <value>The text vertical alignment.</value>
  170. public TextDirection Direction {
  171. get => textDirection;
  172. set {
  173. textDirection = value;
  174. NeedsFormat = true;
  175. }
  176. }
  177. /// <summary>
  178. /// Check if it is a horizontal direction
  179. /// </summary>
  180. public static bool IsHorizontalDirection (TextDirection textDirection)
  181. {
  182. switch (textDirection) {
  183. case TextDirection.LeftRight_TopBottom:
  184. case TextDirection.LeftRight_BottomTop:
  185. case TextDirection.RightLeft_TopBottom:
  186. case TextDirection.RightLeft_BottomTop:
  187. return true;
  188. default:
  189. return false;
  190. }
  191. }
  192. /// <summary>
  193. /// Check if it is a vertical direction
  194. /// </summary>
  195. public static bool IsVerticalDirection (TextDirection textDirection)
  196. {
  197. switch (textDirection) {
  198. case TextDirection.TopBottom_LeftRight:
  199. case TextDirection.TopBottom_RightLeft:
  200. case TextDirection.BottomTop_LeftRight:
  201. case TextDirection.BottomTop_RightLeft:
  202. return true;
  203. default:
  204. return false;
  205. }
  206. }
  207. /// <summary>
  208. /// Check if it is Left to Right direction
  209. /// </summary>
  210. public static bool IsLeftToRight (TextDirection textDirection)
  211. {
  212. switch (textDirection) {
  213. case TextDirection.LeftRight_TopBottom:
  214. case TextDirection.LeftRight_BottomTop:
  215. return true;
  216. default:
  217. return false;
  218. }
  219. }
  220. /// <summary>
  221. /// Check if it is Top to Bottom direction
  222. /// </summary>
  223. public static bool IsTopToBottom (TextDirection textDirection)
  224. {
  225. switch (textDirection) {
  226. case TextDirection.TopBottom_LeftRight:
  227. case TextDirection.TopBottom_RightLeft:
  228. return true;
  229. default:
  230. return false;
  231. }
  232. }
  233. /// <summary>
  234. /// Gets or sets the size of the area the text will be constrained to when formatted.
  235. /// </summary>
  236. public Size Size {
  237. get => size;
  238. set {
  239. size = value;
  240. NeedsFormat = true;
  241. }
  242. }
  243. /// <summary>
  244. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  245. /// </summary>
  246. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  247. /// <summary>
  248. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  249. /// </summary>
  250. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  251. /// <summary>
  252. /// Gets the hotkey. Will be an upper case letter or digit.
  253. /// </summary>
  254. public Key HotKey { get => hotKey; internal set => hotKey = value; }
  255. /// <summary>
  256. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  257. /// the underlying Rune to be identified as a "private use" Unicode character.
  258. /// </summary>HotKeyTagMask
  259. public uint HotKeyTagMask { get; set; } = 0x100000;
  260. /// <summary>
  261. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  262. /// </summary>
  263. public int CursorPosition { get; set; }
  264. /// <summary>
  265. /// Gets the formatted lines.
  266. /// </summary>
  267. /// <remarks>
  268. /// <para>
  269. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  270. /// <see cref="Format(ustring, int, bool, bool, bool, int)"/> will be called internally.
  271. /// </para>
  272. /// </remarks>
  273. public List<ustring> Lines {
  274. get {
  275. // With this check, we protect against subclasses with overrides of Text
  276. if (ustring.IsNullOrEmpty (Text)) {
  277. lines = new List<ustring> ();
  278. lines.Add (ustring.Empty);
  279. NeedsFormat = false;
  280. return lines;
  281. }
  282. if (NeedsFormat) {
  283. var shown_text = text;
  284. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out hotKey)) {
  285. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  286. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  287. }
  288. if (Size.IsEmpty) {
  289. throw new InvalidOperationException ("Size must be set before accessing Lines");
  290. }
  291. if (IsVerticalDirection (textDirection)) {
  292. lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > 1);
  293. if (!AutoSize && lines.Count > Size.Width) {
  294. lines.RemoveRange (Size.Width, lines.Count - Size.Width);
  295. }
  296. } else {
  297. lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1);
  298. if (!AutoSize && lines.Count > Size.Height) {
  299. lines.RemoveRange (Size.Height, lines.Count - Size.Height);
  300. }
  301. }
  302. NeedsFormat = false;
  303. }
  304. return lines;
  305. }
  306. }
  307. /// <summary>
  308. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute)"/> is called.
  309. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  310. /// </summary>
  311. /// <remarks>
  312. /// <para>
  313. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  314. /// </para>
  315. /// </remarks>
  316. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  317. static ustring StripCRLF (ustring str)
  318. {
  319. var runes = str.ToRuneList ();
  320. for (int i = 0; i < runes.Count; i++) {
  321. switch (runes [i]) {
  322. case '\n':
  323. runes.RemoveAt (i);
  324. break;
  325. case '\r':
  326. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  327. runes.RemoveAt (i);
  328. runes.RemoveAt (i + 1);
  329. i++;
  330. } else {
  331. runes.RemoveAt (i);
  332. }
  333. break;
  334. }
  335. }
  336. return ustring.Make (runes);
  337. }
  338. static ustring ReplaceCRLFWithSpace (ustring str)
  339. {
  340. var runes = str.ToRuneList ();
  341. for (int i = 0; i < runes.Count; i++) {
  342. switch (runes [i]) {
  343. case '\n':
  344. runes [i] = (Rune)' ';
  345. break;
  346. case '\r':
  347. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  348. runes [i] = (Rune)' ';
  349. runes.RemoveAt (i + 1);
  350. i++;
  351. } else {
  352. runes [i] = (Rune)' ';
  353. }
  354. break;
  355. }
  356. }
  357. return ustring.Make (runes);
  358. }
  359. /// <summary>
  360. /// Formats the provided text to fit within the width provided using word wrapping.
  361. /// </summary>
  362. /// <param name="text">The text to word wrap</param>
  363. /// <param name="width">The width to contain the text to</param>
  364. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  365. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  366. /// <param name="tabWidth">The tab width.</param>
  367. /// <returns>Returns a list of word wrapped lines.</returns>
  368. /// <remarks>
  369. /// <para>
  370. /// This method does not do any justification.
  371. /// </para>
  372. /// <para>
  373. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  374. /// </para>
  375. /// </remarks>
  376. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0)
  377. {
  378. if (width < 0) {
  379. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  380. }
  381. int start = 0, end;
  382. var lines = new List<ustring> ();
  383. if (ustring.IsNullOrEmpty (text)) {
  384. return lines;
  385. }
  386. var runes = StripCRLF (text).ToRuneList ();
  387. if (!preserveTrailingSpaces) {
  388. while ((end = start + width) < runes.Count) {
  389. while (runes [end] != ' ' && end > start)
  390. end--;
  391. if (end == start)
  392. end = start + width;
  393. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  394. start = end;
  395. if (runes [end] == ' ') {
  396. start++;
  397. }
  398. }
  399. } else {
  400. while ((end = start) < runes.Count) {
  401. end = GetNextWhiteSpace (start, width);
  402. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  403. start = end;
  404. }
  405. }
  406. int GetNextWhiteSpace (int from, int cWidth, int cLength = 0)
  407. {
  408. var to = from;
  409. var length = cLength;
  410. while (length < cWidth && to < runes.Count) {
  411. var rune = runes [to];
  412. length += Rune.ColumnWidth (rune);
  413. if (rune == ' ') {
  414. if (length == cWidth) {
  415. return to + 1;
  416. } else if (length > cWidth) {
  417. return to;
  418. } else {
  419. return GetNextWhiteSpace (to + 1, cWidth, length);
  420. }
  421. } else if (rune == '\t') {
  422. length += tabWidth + 1;
  423. if (length == tabWidth && tabWidth > cWidth) {
  424. return to + 1;
  425. } else if (length > cWidth && tabWidth > cWidth) {
  426. return to;
  427. } else {
  428. return GetNextWhiteSpace (to + 1, cWidth, length);
  429. }
  430. }
  431. to++;
  432. }
  433. if (cLength > 0 && to < runes.Count && runes [to] != ' ') {
  434. return from;
  435. } else {
  436. return to;
  437. }
  438. }
  439. if (start < text.RuneCount) {
  440. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  441. }
  442. return lines;
  443. }
  444. /// <summary>
  445. /// Justifies text within a specified width.
  446. /// </summary>
  447. /// <param name="text">The text to justify.</param>
  448. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  449. /// <param name="talign">Alignment.</param>
  450. /// <returns>Justified and clipped text.</returns>
  451. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign)
  452. {
  453. return ClipAndJustify (text, width, talign == TextAlignment.Justified);
  454. }
  455. /// <summary>
  456. /// Justifies text within a specified width.
  457. /// </summary>
  458. /// <param name="text">The text to justify.</param>
  459. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  460. /// <param name="justify">Justify.</param>
  461. /// <returns>Justified and clipped text.</returns>
  462. public static ustring ClipAndJustify (ustring text, int width, bool justify)
  463. {
  464. if (width < 0) {
  465. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  466. }
  467. if (ustring.IsNullOrEmpty (text)) {
  468. return text;
  469. }
  470. var runes = text.ToRuneList ();
  471. int slen = runes.Count;
  472. if (slen > width) {
  473. return ustring.Make (runes.GetRange (0, width));
  474. } else {
  475. if (justify) {
  476. return Justify (text, width);
  477. }
  478. return text;
  479. }
  480. }
  481. /// <summary>
  482. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  483. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  484. /// </summary>
  485. /// <param name="text"></param>
  486. /// <param name="width"></param>
  487. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  488. /// <returns>The justified text.</returns>
  489. public static ustring Justify (ustring text, int width, char spaceChar = ' ')
  490. {
  491. if (width < 0) {
  492. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  493. }
  494. if (ustring.IsNullOrEmpty (text)) {
  495. return text;
  496. }
  497. var words = text.Split (ustring.Make (' '));
  498. int textCount = words.Sum (arg => arg.RuneCount);
  499. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  500. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  501. var s = new System.Text.StringBuilder ();
  502. for (int w = 0; w < words.Length; w++) {
  503. var x = words [w];
  504. s.Append (x);
  505. if (w + 1 < words.Length)
  506. for (int i = 0; i < spaces; i++)
  507. s.Append (spaceChar);
  508. if (extras > 0) {
  509. extras--;
  510. }
  511. }
  512. return ustring.Make (s.ToString ());
  513. }
  514. static char [] whitespace = new char [] { ' ', '\t' };
  515. private int hotKeyPos;
  516. /// <summary>
  517. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  518. /// </summary>
  519. /// <param name="text"></param>
  520. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  521. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  522. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  523. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  524. /// <param name="tabWidth">The tab width.</param>
  525. /// <returns>A list of word wrapped lines.</returns>
  526. /// <remarks>
  527. /// <para>
  528. /// An empty <c>text</c> string will result in one empty line.
  529. /// </para>
  530. /// <para>
  531. /// If <c>width</c> is 0, a single, empty line will be returned.
  532. /// </para>
  533. /// <para>
  534. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  535. /// </para>
  536. /// </remarks>
  537. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0)
  538. {
  539. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth);
  540. }
  541. /// <summary>
  542. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  543. /// </summary>
  544. /// <param name="text"></param>
  545. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  546. /// <param name="justify">Specifies whether the text should be justified.</param>
  547. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  548. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  549. /// <param name="tabWidth">The tab width.</param>
  550. /// <returns>A list of word wrapped lines.</returns>
  551. /// <remarks>
  552. /// <para>
  553. /// An empty <c>text</c> string will result in one empty line.
  554. /// </para>
  555. /// <para>
  556. /// If <c>width</c> is 0, a single, empty line will be returned.
  557. /// </para>
  558. /// <para>
  559. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  560. /// </para>
  561. /// </remarks>
  562. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  563. bool preserveTrailingSpaces = false, int tabWidth = 0)
  564. {
  565. if (width < 0) {
  566. throw new ArgumentOutOfRangeException ("width cannot be negative");
  567. }
  568. if (preserveTrailingSpaces && !wordWrap) {
  569. throw new ArgumentException ("if 'preserveTrailingSpaces' is true, then 'wordWrap' must be true either.");
  570. }
  571. List<ustring> lineResult = new List<ustring> ();
  572. if (ustring.IsNullOrEmpty (text) || width == 0) {
  573. lineResult.Add (ustring.Empty);
  574. return lineResult;
  575. }
  576. if (wordWrap == false) {
  577. text = ReplaceCRLFWithSpace (text);
  578. lineResult.Add (ClipAndJustify (text, width, justify));
  579. return lineResult;
  580. }
  581. var runes = text.ToRuneList ();
  582. int runeCount = runes.Count;
  583. int lp = 0;
  584. for (int i = 0; i < runeCount; i++) {
  585. Rune c = runes [i];
  586. if (c == '\n') {
  587. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth);
  588. foreach (var line in wrappedLines) {
  589. lineResult.Add (ClipAndJustify (line, width, justify));
  590. }
  591. if (wrappedLines.Count == 0) {
  592. lineResult.Add (ustring.Empty);
  593. }
  594. lp = i + 1;
  595. }
  596. }
  597. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth)) {
  598. lineResult.Add (ClipAndJustify (line, width, justify));
  599. }
  600. return lineResult;
  601. }
  602. /// <summary>
  603. /// Computes the number of lines needed to render the specified text given the width.
  604. /// </summary>
  605. /// <returns>Number of lines.</returns>
  606. /// <param name="text">Text, may contain newlines.</param>
  607. /// <param name="width">The minimum width for the text.</param>
  608. public static int MaxLines (ustring text, int width)
  609. {
  610. var result = TextFormatter.Format (text, width, false, true);
  611. return result.Count;
  612. }
  613. /// <summary>
  614. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  615. /// </summary>
  616. /// <returns>Max width of lines.</returns>
  617. /// <param name="text">Text, may contain newlines.</param>
  618. /// <param name="width">The minimum width for the text.</param>
  619. public static int MaxWidth (ustring text, int width)
  620. {
  621. var result = TextFormatter.Format (text, width, false, true);
  622. var max = 0;
  623. result.ForEach (s => {
  624. var m = 0;
  625. s.ToRuneList ().ForEach (r => m += Rune.ColumnWidth (r));
  626. if (m > max) {
  627. max = m;
  628. }
  629. });
  630. return max;
  631. }
  632. /// <summary>
  633. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  634. /// </summary>
  635. /// <param name="x">The x location of the rectangle</param>
  636. /// <param name="y">The y location of the rectangle</param>
  637. /// <param name="text">The text to measure</param>
  638. /// <param name="direction">The text direction.</param>
  639. /// <returns></returns>
  640. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  641. {
  642. if (ustring.IsNullOrEmpty (text)) {
  643. return new Rect (new Point (x, y), Size.Empty);
  644. }
  645. int w, h;
  646. if (IsHorizontalDirection (direction)) {
  647. int mw = 0;
  648. int ml = 1;
  649. int cols = 0;
  650. foreach (var rune in text) {
  651. if (rune == '\n') {
  652. ml++;
  653. if (cols > mw) {
  654. mw = cols;
  655. }
  656. cols = 0;
  657. } else {
  658. if (rune != '\r') {
  659. cols++;
  660. var rw = Rune.ColumnWidth (rune);
  661. if (rw > 0) {
  662. rw--;
  663. }
  664. cols += rw;
  665. }
  666. }
  667. }
  668. if (cols > mw) {
  669. mw = cols;
  670. }
  671. w = mw;
  672. h = ml;
  673. } else {
  674. int vw = 0;
  675. int vh = 0;
  676. int rows = 0;
  677. foreach (var rune in text) {
  678. if (rune == '\n') {
  679. vw++;
  680. if (rows > vh) {
  681. vh = rows;
  682. }
  683. rows = 0;
  684. } else {
  685. if (rune != '\r') {
  686. rows++;
  687. var rw = Rune.ColumnWidth (rune);
  688. if (rw < 0) {
  689. rw++;
  690. }
  691. if (rw > vw) {
  692. vw = rw;
  693. }
  694. }
  695. }
  696. }
  697. if (rows > vh) {
  698. vh = rows;
  699. }
  700. w = vw;
  701. h = vh;
  702. }
  703. return new Rect (x, y, w, h);
  704. }
  705. /// <summary>
  706. /// Finds the hotkey and its location in text.
  707. /// </summary>
  708. /// <param name="text">The text to look in.</param>
  709. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  710. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  711. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  712. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  713. /// <param name="hotKey">Outputs the hotKey.</param>
  714. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  715. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  716. {
  717. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  718. hotPos = -1;
  719. hotKey = Key.Unknown;
  720. return false;
  721. }
  722. Rune hot_key = (Rune)0;
  723. int hot_pos = -1;
  724. // Use first hot_key char passed into 'hotKey'.
  725. // TODO: Ignore hot_key of two are provided
  726. // TODO: Do not support non-alphanumeric chars that can't be typed
  727. int i = 0;
  728. foreach (Rune c in text) {
  729. if ((char)c != 0xFFFD) {
  730. if (c == hotKeySpecifier) {
  731. hot_pos = i;
  732. } else if (hot_pos > -1) {
  733. hot_key = c;
  734. break;
  735. }
  736. }
  737. i++;
  738. }
  739. // Legacy support - use first upper case char if the specifier was not found
  740. if (hot_pos == -1 && firstUpperCase) {
  741. i = 0;
  742. foreach (Rune c in text) {
  743. if ((char)c != 0xFFFD) {
  744. if (Rune.IsUpper (c)) {
  745. hot_key = c;
  746. hot_pos = i;
  747. break;
  748. }
  749. }
  750. i++;
  751. }
  752. }
  753. if (hot_key != (Rune)0 && hot_pos != -1) {
  754. hotPos = hot_pos;
  755. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  756. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  757. return true;
  758. }
  759. }
  760. hotPos = -1;
  761. hotKey = Key.Unknown;
  762. return false;
  763. }
  764. /// <summary>
  765. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  766. /// it as the hotkey.
  767. /// </summary>
  768. /// <param name="text">The text to tag the hotkey in.</param>
  769. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  770. /// <returns>The text with the hotkey tagged.</returns>
  771. /// <remarks>
  772. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  773. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  774. /// </remarks>
  775. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  776. {
  777. // Set the high bit
  778. var runes = text.ToRuneList ();
  779. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  780. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  781. }
  782. return ustring.Make (runes);
  783. }
  784. /// <summary>
  785. /// Removes the hotkey specifier from text.
  786. /// </summary>
  787. /// <param name="text">The text to manipulate.</param>
  788. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  789. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  790. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  791. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  792. {
  793. if (ustring.IsNullOrEmpty (text)) {
  794. return text;
  795. }
  796. // Scan
  797. ustring start = ustring.Empty;
  798. int i = 0;
  799. foreach (Rune c in text) {
  800. if (c == hotKeySpecifier && i == hotPos) {
  801. i++;
  802. continue;
  803. }
  804. start += ustring.Make (c);
  805. i++;
  806. }
  807. return start;
  808. }
  809. /// <summary>
  810. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  811. /// </summary>
  812. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  813. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  814. /// <param name="hotColor">The color to use to draw the hotkey</param>
  815. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor)
  816. {
  817. // With this check, we protect against subclasses with overrides of Text (like Button)
  818. if (ustring.IsNullOrEmpty (text)) {
  819. return;
  820. }
  821. Application.Driver?.SetAttribute (normalColor);
  822. // Use "Lines" to ensure a Format (don't use "lines"))
  823. var linesFormated = Lines;
  824. switch (textDirection) {
  825. case TextDirection.TopBottom_RightLeft:
  826. case TextDirection.LeftRight_BottomTop:
  827. case TextDirection.RightLeft_BottomTop:
  828. case TextDirection.BottomTop_RightLeft:
  829. linesFormated.Reverse ();
  830. break;
  831. }
  832. for (int line = 0; line < linesFormated.Count; line++) {
  833. var isVertical = IsVerticalDirection (textDirection);
  834. if ((isVertical && (line > bounds.Width)) || (!isVertical && (line > bounds.Height)))
  835. continue;
  836. var runes = lines [line].ToRunes ();
  837. switch (textDirection) {
  838. case TextDirection.RightLeft_BottomTop:
  839. case TextDirection.RightLeft_TopBottom:
  840. case TextDirection.BottomTop_LeftRight:
  841. case TextDirection.BottomTop_RightLeft:
  842. runes = runes.Reverse ().ToArray ();
  843. break;
  844. }
  845. // When text is justified, we lost left or right, so we use the direction to align.
  846. int x, y;
  847. // Horizontal Alignment
  848. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  849. if (isVertical) {
  850. x = bounds.Right - Lines.Count + line;
  851. CursorPosition = bounds.Width - Lines.Count + hotKeyPos;
  852. } else {
  853. x = bounds.Right - runes.Length;
  854. CursorPosition = bounds.Width - runes.Length + hotKeyPos;
  855. }
  856. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  857. if (isVertical) {
  858. x = bounds.Left + line;
  859. } else {
  860. x = bounds.Left;
  861. }
  862. CursorPosition = hotKeyPos;
  863. } else if (textAlignment == TextAlignment.Centered) {
  864. if (isVertical) {
  865. x = bounds.Left + line + ((bounds.Width - Lines.Count) / 2);
  866. CursorPosition = (bounds.Width - Lines.Count) / 2 + hotKeyPos;
  867. } else {
  868. x = bounds.Left + (bounds.Width - runes.Length) / 2;
  869. CursorPosition = (bounds.Width - runes.Length) / 2 + hotKeyPos;
  870. }
  871. } else {
  872. throw new ArgumentOutOfRangeException ();
  873. }
  874. // Vertical Alignment
  875. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  876. if (isVertical) {
  877. y = bounds.Bottom - runes.Length;
  878. } else {
  879. y = bounds.Bottom - Lines.Count + line;
  880. }
  881. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  882. if (isVertical) {
  883. y = bounds.Top;
  884. } else {
  885. y = bounds.Top + line;
  886. }
  887. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  888. if (isVertical) {
  889. var s = (bounds.Height - runes.Length) / 2;
  890. y = bounds.Top + s;
  891. } else {
  892. var s = (bounds.Height - Lines.Count) / 2;
  893. y = bounds.Top + line + s;
  894. }
  895. } else {
  896. throw new ArgumentOutOfRangeException ();
  897. }
  898. var start = isVertical ? bounds.Top : bounds.Left;
  899. var size = isVertical ? bounds.Height : bounds.Width;
  900. var current = start;
  901. for (var idx = start; idx < start + size; idx++) {
  902. if (idx < 0) {
  903. current++;
  904. continue;
  905. }
  906. var rune = (Rune)' ';
  907. if (isVertical) {
  908. Application.Driver?.Move (x, current);
  909. if (idx >= y && idx < (y + runes.Length)) {
  910. rune = runes [idx - y];
  911. }
  912. } else {
  913. Application.Driver?.Move (current, y);
  914. if (idx >= x && idx < (x + runes.Length)) {
  915. rune = runes [idx - x];
  916. }
  917. }
  918. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  919. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  920. (!isVertical && textAlignment == TextAlignment.Justified)) {
  921. CursorPosition = idx - start;
  922. }
  923. Application.Driver?.SetAttribute (hotColor);
  924. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  925. Application.Driver?.SetAttribute (normalColor);
  926. } else {
  927. Application.Driver?.AddRune (rune);
  928. }
  929. current += Rune.ColumnWidth (rune);
  930. if (idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > size) {
  931. break;
  932. }
  933. }
  934. }
  935. }
  936. }
  937. }