TextFormatter.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. /// Adds trailing whitespace or truncates <paramref name="text"/>
  361. /// so that it fits exactly <paramref name="width"/> console units.
  362. /// Note that some unicode characters take 2+ columns
  363. /// </summary>
  364. /// <param name="text"></param>
  365. /// <param name="width"></param>
  366. /// <returns></returns>
  367. public static string ClipOrPad (string text, int width)
  368. {
  369. if (string.IsNullOrEmpty (text))
  370. return text;
  371. // if value is not wide enough
  372. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  373. // pad it out with spaces to the given alignment
  374. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  375. return text + new string (' ', toPad);
  376. }
  377. // value is too wide
  378. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  379. }
  380. /// <summary>
  381. /// Formats the provided text to fit within the width provided using word wrapping.
  382. /// </summary>
  383. /// <param name="text">The text to word wrap</param>
  384. /// <param name="width">The width to contain the text to</param>
  385. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  386. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  387. /// <param name="tabWidth">The tab width.</param>
  388. /// <returns>Returns a list of word wrapped lines.</returns>
  389. /// <remarks>
  390. /// <para>
  391. /// This method does not do any justification.
  392. /// </para>
  393. /// <para>
  394. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  395. /// </para>
  396. /// </remarks>
  397. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0)
  398. {
  399. if (width < 0) {
  400. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  401. }
  402. int start = 0, end;
  403. var lines = new List<ustring> ();
  404. if (ustring.IsNullOrEmpty (text)) {
  405. return lines;
  406. }
  407. var runes = StripCRLF (text).ToRuneList ();
  408. if (!preserveTrailingSpaces) {
  409. while ((end = start + width) < runes.Count) {
  410. while (runes [end] != ' ' && end > start)
  411. end--;
  412. if (end == start)
  413. end = start + width;
  414. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  415. start = end;
  416. if (runes [end] == ' ') {
  417. start++;
  418. }
  419. }
  420. } else {
  421. while ((end = start) < runes.Count) {
  422. end = GetNextWhiteSpace (start, width);
  423. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  424. start = end;
  425. }
  426. }
  427. int GetNextWhiteSpace (int from, int cWidth, int cLength = 0)
  428. {
  429. var to = from;
  430. var length = cLength;
  431. while (length < cWidth && to < runes.Count) {
  432. var rune = runes [to];
  433. length += Rune.ColumnWidth (rune);
  434. if (rune == ' ') {
  435. if (length == cWidth) {
  436. return to + 1;
  437. } else if (length > cWidth) {
  438. return to;
  439. } else {
  440. return GetNextWhiteSpace (to + 1, cWidth, length);
  441. }
  442. } else if (rune == '\t') {
  443. length += tabWidth + 1;
  444. if (length == tabWidth && tabWidth > cWidth) {
  445. return to + 1;
  446. } else if (length > cWidth && tabWidth > cWidth) {
  447. return to;
  448. } else {
  449. return GetNextWhiteSpace (to + 1, cWidth, length);
  450. }
  451. }
  452. to++;
  453. }
  454. if (cLength > 0 && to < runes.Count && runes [to] != ' ') {
  455. return from;
  456. } else {
  457. return to;
  458. }
  459. }
  460. if (start < text.RuneCount) {
  461. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  462. }
  463. return lines;
  464. }
  465. /// <summary>
  466. /// Justifies text within a specified width.
  467. /// </summary>
  468. /// <param name="text">The text to justify.</param>
  469. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  470. /// <param name="talign">Alignment.</param>
  471. /// <returns>Justified and clipped text.</returns>
  472. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign)
  473. {
  474. return ClipAndJustify (text, width, talign == TextAlignment.Justified);
  475. }
  476. /// <summary>
  477. /// Justifies text within a specified width.
  478. /// </summary>
  479. /// <param name="text">The text to justify.</param>
  480. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  481. /// <param name="justify">Justify.</param>
  482. /// <returns>Justified and clipped text.</returns>
  483. public static ustring ClipAndJustify (ustring text, int width, bool justify)
  484. {
  485. if (width < 0) {
  486. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  487. }
  488. if (ustring.IsNullOrEmpty (text)) {
  489. return text;
  490. }
  491. var runes = text.ToRuneList ();
  492. int slen = runes.Count;
  493. if (slen > width) {
  494. return ustring.Make (runes.GetRange (0, width));
  495. } else {
  496. if (justify) {
  497. return Justify (text, width);
  498. }
  499. return text;
  500. }
  501. }
  502. /// <summary>
  503. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  504. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  505. /// </summary>
  506. /// <param name="text"></param>
  507. /// <param name="width"></param>
  508. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  509. /// <returns>The justified text.</returns>
  510. public static ustring Justify (ustring text, int width, char spaceChar = ' ')
  511. {
  512. if (width < 0) {
  513. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  514. }
  515. if (ustring.IsNullOrEmpty (text)) {
  516. return text;
  517. }
  518. var words = text.Split (ustring.Make (' '));
  519. int textCount = words.Sum (arg => arg.RuneCount);
  520. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  521. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  522. var s = new System.Text.StringBuilder ();
  523. for (int w = 0; w < words.Length; w++) {
  524. var x = words [w];
  525. s.Append (x);
  526. if (w + 1 < words.Length)
  527. for (int i = 0; i < spaces; i++)
  528. s.Append (spaceChar);
  529. if (extras > 0) {
  530. extras--;
  531. }
  532. }
  533. return ustring.Make (s.ToString ());
  534. }
  535. static char [] whitespace = new char [] { ' ', '\t' };
  536. private int hotKeyPos;
  537. /// <summary>
  538. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  539. /// </summary>
  540. /// <param name="text"></param>
  541. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  542. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  543. /// <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>
  544. /// <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>
  545. /// <param name="tabWidth">The tab width.</param>
  546. /// <returns>A list of word wrapped lines.</returns>
  547. /// <remarks>
  548. /// <para>
  549. /// An empty <c>text</c> string will result in one empty line.
  550. /// </para>
  551. /// <para>
  552. /// If <c>width</c> is 0, a single, empty line will be returned.
  553. /// </para>
  554. /// <para>
  555. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  556. /// </para>
  557. /// </remarks>
  558. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0)
  559. {
  560. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth);
  561. }
  562. /// <summary>
  563. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  564. /// </summary>
  565. /// <param name="text"></param>
  566. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  567. /// <param name="justify">Specifies whether the text should be justified.</param>
  568. /// <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>
  569. /// <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>
  570. /// <param name="tabWidth">The tab width.</param>
  571. /// <returns>A list of word wrapped lines.</returns>
  572. /// <remarks>
  573. /// <para>
  574. /// An empty <c>text</c> string will result in one empty line.
  575. /// </para>
  576. /// <para>
  577. /// If <c>width</c> is 0, a single, empty line will be returned.
  578. /// </para>
  579. /// <para>
  580. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  581. /// </para>
  582. /// </remarks>
  583. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  584. bool preserveTrailingSpaces = false, int tabWidth = 0)
  585. {
  586. if (width < 0) {
  587. throw new ArgumentOutOfRangeException ("width cannot be negative");
  588. }
  589. if (preserveTrailingSpaces && !wordWrap) {
  590. throw new ArgumentException ("if 'preserveTrailingSpaces' is true, then 'wordWrap' must be true either.");
  591. }
  592. List<ustring> lineResult = new List<ustring> ();
  593. if (ustring.IsNullOrEmpty (text) || width == 0) {
  594. lineResult.Add (ustring.Empty);
  595. return lineResult;
  596. }
  597. if (wordWrap == false) {
  598. text = ReplaceCRLFWithSpace (text);
  599. lineResult.Add (ClipAndJustify (text, width, justify));
  600. return lineResult;
  601. }
  602. var runes = text.ToRuneList ();
  603. int runeCount = runes.Count;
  604. int lp = 0;
  605. for (int i = 0; i < runeCount; i++) {
  606. Rune c = runes [i];
  607. if (c == '\n') {
  608. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth);
  609. foreach (var line in wrappedLines) {
  610. lineResult.Add (ClipAndJustify (line, width, justify));
  611. }
  612. if (wrappedLines.Count == 0) {
  613. lineResult.Add (ustring.Empty);
  614. }
  615. lp = i + 1;
  616. }
  617. }
  618. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth)) {
  619. lineResult.Add (ClipAndJustify (line, width, justify));
  620. }
  621. return lineResult;
  622. }
  623. /// <summary>
  624. /// Computes the number of lines needed to render the specified text given the width.
  625. /// </summary>
  626. /// <returns>Number of lines.</returns>
  627. /// <param name="text">Text, may contain newlines.</param>
  628. /// <param name="width">The minimum width for the text.</param>
  629. public static int MaxLines (ustring text, int width)
  630. {
  631. var result = TextFormatter.Format (text, width, false, true);
  632. return result.Count;
  633. }
  634. /// <summary>
  635. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  636. /// </summary>
  637. /// <returns>Max width of lines.</returns>
  638. /// <param name="text">Text, may contain newlines.</param>
  639. /// <param name="width">The minimum width for the text.</param>
  640. public static int MaxWidth (ustring text, int width)
  641. {
  642. var result = TextFormatter.Format (text, width, false, true);
  643. var max = 0;
  644. result.ForEach (s => {
  645. var m = 0;
  646. s.ToRuneList ().ForEach (r => m += Rune.ColumnWidth (r));
  647. if (m > max) {
  648. max = m;
  649. }
  650. });
  651. return max;
  652. }
  653. /// <summary>
  654. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  655. /// </summary>
  656. /// <param name="x">The x location of the rectangle</param>
  657. /// <param name="y">The y location of the rectangle</param>
  658. /// <param name="text">The text to measure</param>
  659. /// <param name="direction">The text direction.</param>
  660. /// <returns></returns>
  661. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  662. {
  663. if (ustring.IsNullOrEmpty (text)) {
  664. return new Rect (new Point (x, y), Size.Empty);
  665. }
  666. int w, h;
  667. if (IsHorizontalDirection (direction)) {
  668. int mw = 0;
  669. int ml = 1;
  670. int cols = 0;
  671. foreach (var rune in text) {
  672. if (rune == '\n') {
  673. ml++;
  674. if (cols > mw) {
  675. mw = cols;
  676. }
  677. cols = 0;
  678. } else {
  679. if (rune != '\r') {
  680. cols++;
  681. var rw = Rune.ColumnWidth (rune);
  682. if (rw > 0) {
  683. rw--;
  684. }
  685. cols += rw;
  686. }
  687. }
  688. }
  689. if (cols > mw) {
  690. mw = cols;
  691. }
  692. w = mw;
  693. h = ml;
  694. } else {
  695. int vw = 0;
  696. int vh = 0;
  697. int rows = 0;
  698. foreach (var rune in text) {
  699. if (rune == '\n') {
  700. vw++;
  701. if (rows > vh) {
  702. vh = rows;
  703. }
  704. rows = 0;
  705. } else {
  706. if (rune != '\r') {
  707. rows++;
  708. var rw = Rune.ColumnWidth (rune);
  709. if (rw < 0) {
  710. rw++;
  711. }
  712. if (rw > vw) {
  713. vw = rw;
  714. }
  715. }
  716. }
  717. }
  718. if (rows > vh) {
  719. vh = rows;
  720. }
  721. w = vw;
  722. h = vh;
  723. }
  724. return new Rect (x, y, w, h);
  725. }
  726. /// <summary>
  727. /// Finds the hotkey and its location in text.
  728. /// </summary>
  729. /// <param name="text">The text to look in.</param>
  730. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  731. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  732. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  733. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  734. /// <param name="hotKey">Outputs the hotKey.</param>
  735. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  736. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  737. {
  738. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  739. hotPos = -1;
  740. hotKey = Key.Unknown;
  741. return false;
  742. }
  743. Rune hot_key = (Rune)0;
  744. int hot_pos = -1;
  745. // Use first hot_key char passed into 'hotKey'.
  746. // TODO: Ignore hot_key of two are provided
  747. // TODO: Do not support non-alphanumeric chars that can't be typed
  748. int i = 0;
  749. foreach (Rune c in text) {
  750. if ((char)c != 0xFFFD) {
  751. if (c == hotKeySpecifier) {
  752. hot_pos = i;
  753. } else if (hot_pos > -1) {
  754. hot_key = c;
  755. break;
  756. }
  757. }
  758. i++;
  759. }
  760. // Legacy support - use first upper case char if the specifier was not found
  761. if (hot_pos == -1 && firstUpperCase) {
  762. i = 0;
  763. foreach (Rune c in text) {
  764. if ((char)c != 0xFFFD) {
  765. if (Rune.IsUpper (c)) {
  766. hot_key = c;
  767. hot_pos = i;
  768. break;
  769. }
  770. }
  771. i++;
  772. }
  773. }
  774. if (hot_key != (Rune)0 && hot_pos != -1) {
  775. hotPos = hot_pos;
  776. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  777. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  778. return true;
  779. }
  780. }
  781. hotPos = -1;
  782. hotKey = Key.Unknown;
  783. return false;
  784. }
  785. /// <summary>
  786. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  787. /// it as the hotkey.
  788. /// </summary>
  789. /// <param name="text">The text to tag the hotkey in.</param>
  790. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  791. /// <returns>The text with the hotkey tagged.</returns>
  792. /// <remarks>
  793. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  794. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  795. /// </remarks>
  796. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  797. {
  798. // Set the high bit
  799. var runes = text.ToRuneList ();
  800. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  801. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  802. }
  803. return ustring.Make (runes);
  804. }
  805. /// <summary>
  806. /// Removes the hotkey specifier from text.
  807. /// </summary>
  808. /// <param name="text">The text to manipulate.</param>
  809. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  810. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  811. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  812. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  813. {
  814. if (ustring.IsNullOrEmpty (text)) {
  815. return text;
  816. }
  817. // Scan
  818. ustring start = ustring.Empty;
  819. int i = 0;
  820. foreach (Rune c in text) {
  821. if (c == hotKeySpecifier && i == hotPos) {
  822. i++;
  823. continue;
  824. }
  825. start += ustring.Make (c);
  826. i++;
  827. }
  828. return start;
  829. }
  830. /// <summary>
  831. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  832. /// </summary>
  833. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  834. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  835. /// <param name="hotColor">The color to use to draw the hotkey</param>
  836. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor)
  837. {
  838. // With this check, we protect against subclasses with overrides of Text (like Button)
  839. if (ustring.IsNullOrEmpty (text)) {
  840. return;
  841. }
  842. Application.Driver?.SetAttribute (normalColor);
  843. // Use "Lines" to ensure a Format (don't use "lines"))
  844. var linesFormated = Lines;
  845. switch (textDirection) {
  846. case TextDirection.TopBottom_RightLeft:
  847. case TextDirection.LeftRight_BottomTop:
  848. case TextDirection.RightLeft_BottomTop:
  849. case TextDirection.BottomTop_RightLeft:
  850. linesFormated.Reverse ();
  851. break;
  852. }
  853. for (int line = 0; line < linesFormated.Count; line++) {
  854. var isVertical = IsVerticalDirection (textDirection);
  855. if ((isVertical && (line > bounds.Width)) || (!isVertical && (line > bounds.Height)))
  856. continue;
  857. var runes = lines [line].ToRunes ();
  858. switch (textDirection) {
  859. case TextDirection.RightLeft_BottomTop:
  860. case TextDirection.RightLeft_TopBottom:
  861. case TextDirection.BottomTop_LeftRight:
  862. case TextDirection.BottomTop_RightLeft:
  863. runes = runes.Reverse ().ToArray ();
  864. break;
  865. }
  866. // When text is justified, we lost left or right, so we use the direction to align.
  867. int x, y;
  868. // Horizontal Alignment
  869. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  870. if (isVertical) {
  871. x = bounds.Right - Lines.Count + line;
  872. CursorPosition = bounds.Width - Lines.Count + hotKeyPos;
  873. } else {
  874. x = bounds.Right - runes.Length;
  875. CursorPosition = bounds.Width - runes.Length + hotKeyPos;
  876. }
  877. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  878. if (isVertical) {
  879. x = bounds.Left + line;
  880. } else {
  881. x = bounds.Left;
  882. }
  883. CursorPosition = hotKeyPos;
  884. } else if (textAlignment == TextAlignment.Centered) {
  885. if (isVertical) {
  886. x = bounds.Left + line + ((bounds.Width - Lines.Count) / 2);
  887. CursorPosition = (bounds.Width - Lines.Count) / 2 + hotKeyPos;
  888. } else {
  889. x = bounds.Left + (bounds.Width - runes.Length) / 2;
  890. CursorPosition = (bounds.Width - runes.Length) / 2 + hotKeyPos;
  891. }
  892. } else {
  893. throw new ArgumentOutOfRangeException ();
  894. }
  895. // Vertical Alignment
  896. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  897. if (isVertical) {
  898. y = bounds.Bottom - runes.Length;
  899. } else {
  900. y = bounds.Bottom - Lines.Count + line;
  901. }
  902. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  903. if (isVertical) {
  904. y = bounds.Top;
  905. } else {
  906. y = bounds.Top + line;
  907. }
  908. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  909. if (isVertical) {
  910. var s = (bounds.Height - runes.Length) / 2;
  911. y = bounds.Top + s;
  912. } else {
  913. var s = (bounds.Height - Lines.Count) / 2;
  914. y = bounds.Top + line + s;
  915. }
  916. } else {
  917. throw new ArgumentOutOfRangeException ();
  918. }
  919. var start = isVertical ? bounds.Top : bounds.Left;
  920. var size = isVertical ? bounds.Height : bounds.Width;
  921. var current = start;
  922. for (var idx = start; idx < start + size; idx++) {
  923. if (idx < 0) {
  924. current++;
  925. continue;
  926. }
  927. var rune = (Rune)' ';
  928. if (isVertical) {
  929. Application.Driver?.Move (x, current);
  930. if (idx >= y && idx < (y + runes.Length)) {
  931. rune = runes [idx - y];
  932. }
  933. } else {
  934. Application.Driver?.Move (current, y);
  935. if (idx >= x && idx < (x + runes.Length)) {
  936. rune = runes [idx - x];
  937. }
  938. }
  939. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  940. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  941. (!isVertical && textAlignment == TextAlignment.Justified)) {
  942. CursorPosition = idx - start;
  943. }
  944. Application.Driver?.SetAttribute (hotColor);
  945. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  946. Application.Driver?.SetAttribute (normalColor);
  947. } else {
  948. Application.Driver?.AddRune (rune);
  949. }
  950. current += Rune.ColumnWidth (rune);
  951. if (idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > size) {
  952. break;
  953. }
  954. }
  955. }
  956. }
  957. }
  958. }