TextFormatter.cs 28 KB

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