TextFormatter.cs 29 KB

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