TextFormatter.cs 30 KB

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