TextFormatter.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. /// Event invoked when the <see cref="HotKey"/> is changed.
  123. /// </summary>
  124. public event Action<Key> HotKeyChanged;
  125. /// <summary>
  126. /// The text to be displayed. This text is never modified.
  127. /// </summary>
  128. public virtual ustring Text {
  129. get => text;
  130. set {
  131. text = value;
  132. if (text != null && text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.ConsoleWidth)) {
  133. // Provide a default size (width = length of longest line, height = 1)
  134. // TODO: It might makes more sense for the default to be width = length of first line?
  135. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  136. }
  137. NeedsFormat = true;
  138. }
  139. }
  140. /// <summary>
  141. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  142. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  143. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  144. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  145. /// </summary>
  146. public bool AutoSize { get; set; }
  147. /// <summary>
  148. /// Gets or sets a flag that determines whether <see cref="Text"/> will have trailing spaces preserved
  149. /// or not when <see cref="WordWrap"/> is enabled. If `true` any trailing spaces will be trimmed when
  150. /// either the <see cref="Text"/> property is changed or when <see cref="WordWrap"/> is set to `true`.
  151. /// The default is `false`.
  152. /// </summary>
  153. public bool PreserveTrailingSpaces { get; set; }
  154. /// <summary>
  155. /// Controls the horizontal text-alignment property.
  156. /// </summary>
  157. /// <value>The text alignment.</value>
  158. public TextAlignment Alignment {
  159. get => textAlignment;
  160. set {
  161. textAlignment = value;
  162. NeedsFormat = true;
  163. }
  164. }
  165. /// <summary>
  166. /// Controls the vertical text-alignment property.
  167. /// </summary>
  168. /// <value>The text vertical alignment.</value>
  169. public VerticalTextAlignment VerticalAlignment {
  170. get => textVerticalAlignment;
  171. set {
  172. textVerticalAlignment = value;
  173. NeedsFormat = true;
  174. }
  175. }
  176. /// <summary>
  177. /// Controls the text-direction property.
  178. /// </summary>
  179. /// <value>The text vertical alignment.</value>
  180. public TextDirection Direction {
  181. get => textDirection;
  182. set {
  183. textDirection = value;
  184. NeedsFormat = true;
  185. }
  186. }
  187. /// <summary>
  188. /// Check if it is a horizontal direction
  189. /// </summary>
  190. public static bool IsHorizontalDirection (TextDirection textDirection)
  191. {
  192. switch (textDirection) {
  193. case TextDirection.LeftRight_TopBottom:
  194. case TextDirection.LeftRight_BottomTop:
  195. case TextDirection.RightLeft_TopBottom:
  196. case TextDirection.RightLeft_BottomTop:
  197. return true;
  198. default:
  199. return false;
  200. }
  201. }
  202. /// <summary>
  203. /// Check if it is a vertical direction
  204. /// </summary>
  205. public static bool IsVerticalDirection (TextDirection textDirection)
  206. {
  207. switch (textDirection) {
  208. case TextDirection.TopBottom_LeftRight:
  209. case TextDirection.TopBottom_RightLeft:
  210. case TextDirection.BottomTop_LeftRight:
  211. case TextDirection.BottomTop_RightLeft:
  212. return true;
  213. default:
  214. return false;
  215. }
  216. }
  217. /// <summary>
  218. /// Check if it is Left to Right direction
  219. /// </summary>
  220. public static bool IsLeftToRight (TextDirection textDirection)
  221. {
  222. switch (textDirection) {
  223. case TextDirection.LeftRight_TopBottom:
  224. case TextDirection.LeftRight_BottomTop:
  225. return true;
  226. default:
  227. return false;
  228. }
  229. }
  230. /// <summary>
  231. /// Check if it is Top to Bottom direction
  232. /// </summary>
  233. public static bool IsTopToBottom (TextDirection textDirection)
  234. {
  235. switch (textDirection) {
  236. case TextDirection.TopBottom_LeftRight:
  237. case TextDirection.TopBottom_RightLeft:
  238. return true;
  239. default:
  240. return false;
  241. }
  242. }
  243. /// <summary>
  244. /// Gets or sets the size of the area the text will be constrained to when formatted.
  245. /// </summary>
  246. public Size Size {
  247. get => size;
  248. set {
  249. size = value;
  250. NeedsFormat = true;
  251. }
  252. }
  253. /// <summary>
  254. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  255. /// </summary>
  256. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  257. /// <summary>
  258. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  259. /// </summary>
  260. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  261. /// <summary>
  262. /// Gets the hotkey. Will be an upper case letter or digit.
  263. /// </summary>
  264. public Key HotKey {
  265. get => hotKey;
  266. internal set {
  267. if (hotKey != value) {
  268. var oldKey = hotKey;
  269. hotKey = value;
  270. HotKeyChanged?.Invoke (oldKey);
  271. }
  272. }
  273. }
  274. /// <summary>
  275. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  276. /// the underlying Rune to be identified as a "private use" Unicode character.
  277. /// </summary>HotKeyTagMask
  278. public uint HotKeyTagMask { get; set; } = 0x100000;
  279. /// <summary>
  280. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  281. /// </summary>
  282. public int CursorPosition { get; set; }
  283. /// <summary>
  284. /// Gets the formatted lines.
  285. /// </summary>
  286. /// <remarks>
  287. /// <para>
  288. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  289. /// <see cref="Format(ustring, int, bool, bool, bool, int, TextDirection)"/> will be called internally.
  290. /// </para>
  291. /// </remarks>
  292. public List<ustring> Lines {
  293. get {
  294. // With this check, we protect against subclasses with overrides of Text
  295. if (ustring.IsNullOrEmpty (Text) || Size.IsEmpty) {
  296. lines = new List<ustring> ();
  297. lines.Add (ustring.Empty);
  298. NeedsFormat = false;
  299. return lines;
  300. }
  301. if (NeedsFormat) {
  302. var shown_text = text;
  303. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out Key newHotKey)) {
  304. HotKey = newHotKey;
  305. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  306. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  307. }
  308. if (IsVerticalDirection (textDirection)) {
  309. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1);
  310. lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth,
  311. PreserveTrailingSpaces, 0, textDirection);
  312. if (!AutoSize) {
  313. colsWidth = GetMaxColsForWidth (lines, Size.Width);
  314. if (lines.Count > colsWidth) {
  315. lines.RemoveRange (colsWidth, lines.Count - colsWidth);
  316. }
  317. }
  318. } else {
  319. lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1,
  320. PreserveTrailingSpaces, 0, textDirection);
  321. if (!AutoSize && lines.Count > Size.Height) {
  322. lines.RemoveRange (Size.Height, lines.Count - Size.Height);
  323. }
  324. }
  325. NeedsFormat = false;
  326. }
  327. return lines;
  328. }
  329. }
  330. /// <summary>
  331. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect)"/> is called.
  332. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  333. /// </summary>
  334. /// <remarks>
  335. /// <para>
  336. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  337. /// </para>
  338. /// </remarks>
  339. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  340. static ustring StripCRLF (ustring str, bool keepNewLine = false)
  341. {
  342. var runes = str.ToRuneList ();
  343. for (int i = 0; i < runes.Count; i++) {
  344. switch (runes [i]) {
  345. case '\n':
  346. if (!keepNewLine) {
  347. runes.RemoveAt (i);
  348. }
  349. break;
  350. case '\r':
  351. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  352. runes.RemoveAt (i);
  353. if (!keepNewLine) {
  354. runes.RemoveAt (i);
  355. }
  356. i++;
  357. } else {
  358. if (!keepNewLine) {
  359. runes.RemoveAt (i);
  360. }
  361. }
  362. break;
  363. }
  364. }
  365. return ustring.Make (runes);
  366. }
  367. static ustring ReplaceCRLFWithSpace (ustring str)
  368. {
  369. var runes = str.ToRuneList ();
  370. for (int i = 0; i < runes.Count; i++) {
  371. switch (runes [i]) {
  372. case '\n':
  373. runes [i] = (Rune)' ';
  374. break;
  375. case '\r':
  376. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  377. runes [i] = (Rune)' ';
  378. runes.RemoveAt (i + 1);
  379. i++;
  380. } else {
  381. runes [i] = (Rune)' ';
  382. }
  383. break;
  384. }
  385. }
  386. return ustring.Make (runes);
  387. }
  388. /// <summary>
  389. /// Splits all newlines in the <paramref name="text"/> into a list
  390. /// and supports both CRLF and LF, preserving the ending newline.
  391. /// </summary>
  392. /// <param name="text">The text.</param>
  393. /// <returns>A list of text without the newline characters.</returns>
  394. public static List<ustring> SplitNewLine (ustring text)
  395. {
  396. var runes = text.ToRuneList ();
  397. var lines = new List<ustring> ();
  398. var start = 0;
  399. var end = 0;
  400. for (int i = 0; i < runes.Count; i++) {
  401. end = i;
  402. switch (runes [i]) {
  403. case '\n':
  404. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  405. i++;
  406. start = i;
  407. break;
  408. case '\r':
  409. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  410. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  411. i += 2;
  412. start = i;
  413. } else {
  414. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  415. i++;
  416. start = i;
  417. }
  418. break;
  419. }
  420. }
  421. if (runes.Count > 0 && lines.Count == 0) {
  422. lines.Add (ustring.Make (runes));
  423. } else if (runes.Count > 0 && start < runes.Count) {
  424. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  425. } else {
  426. lines.Add (ustring.Make (""));
  427. }
  428. return lines;
  429. }
  430. /// <summary>
  431. /// Adds trailing whitespace or truncates <paramref name="text"/>
  432. /// so that it fits exactly <paramref name="width"/> console units.
  433. /// Note that some unicode characters take 2+ columns
  434. /// </summary>
  435. /// <param name="text"></param>
  436. /// <param name="width"></param>
  437. /// <returns></returns>
  438. public static string ClipOrPad (string text, int width)
  439. {
  440. if (string.IsNullOrEmpty (text))
  441. return text;
  442. // if value is not wide enough
  443. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  444. // pad it out with spaces to the given alignment
  445. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  446. return text + new string (' ', toPad);
  447. }
  448. // value is too wide
  449. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  450. }
  451. /// <summary>
  452. /// Formats the provided text to fit within the width provided using word wrapping.
  453. /// </summary>
  454. /// <param name="text">The text to word wrap</param>
  455. /// <param name="width">The width to contain the text to</param>
  456. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  457. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  458. /// <param name="tabWidth">The tab width.</param>
  459. /// <param name="textDirection">The text direction.</param>
  460. /// <returns>Returns a list of word wrapped lines.</returns>
  461. /// <remarks>
  462. /// <para>
  463. /// This method does not do any justification.
  464. /// </para>
  465. /// <para>
  466. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  467. /// </para>
  468. /// </remarks>
  469. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  470. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  471. {
  472. if (width < 0) {
  473. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  474. }
  475. int start = 0, end;
  476. var lines = new List<ustring> ();
  477. if (ustring.IsNullOrEmpty (text)) {
  478. return lines;
  479. }
  480. var runes = StripCRLF (text).ToRuneList ();
  481. if (!preserveTrailingSpaces) {
  482. if (IsHorizontalDirection (textDirection)) {
  483. while ((end = start + Math.Max (GetMaxLengthForWidth (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
  484. while (runes [end] != ' ' && end > start)
  485. end--;
  486. if (end == start)
  487. end = start + GetMaxLengthForWidth (runes.GetRange (end, runes.Count - end), width);
  488. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  489. start = end;
  490. if (runes [end] == ' ') {
  491. start++;
  492. }
  493. }
  494. } else {
  495. while ((end = start + width) < runes.Count) {
  496. while (runes [end] != ' ' && end > start)
  497. end--;
  498. if (end == start)
  499. end = start + width;
  500. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  501. start = end;
  502. if (runes [end] == ' ') {
  503. start++;
  504. }
  505. }
  506. }
  507. } else {
  508. while ((end = start) < runes.Count) {
  509. end = GetNextWhiteSpace (start, width, out bool incomplete);
  510. if (end == 0 && incomplete) {
  511. start = text.RuneCount;
  512. break;
  513. }
  514. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  515. start = end;
  516. if (incomplete) {
  517. start = text.RuneCount;
  518. break;
  519. }
  520. }
  521. }
  522. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  523. {
  524. var lastFrom = from;
  525. var to = from;
  526. var length = cLength;
  527. incomplete = false;
  528. while (length < cWidth && to < runes.Count) {
  529. var rune = runes [to];
  530. if (IsHorizontalDirection (textDirection)) {
  531. length += Rune.ColumnWidth (rune);
  532. } else {
  533. length++;
  534. }
  535. if (length > cWidth) {
  536. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  537. incomplete = true;
  538. }
  539. return to;
  540. }
  541. if (rune == ' ') {
  542. if (length == cWidth) {
  543. return to + 1;
  544. } else if (length > cWidth) {
  545. return to;
  546. } else {
  547. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  548. }
  549. } else if (rune == '\t') {
  550. length += tabWidth + 1;
  551. if (length == tabWidth && tabWidth > cWidth) {
  552. return to + 1;
  553. } else if (length > cWidth && tabWidth > cWidth) {
  554. return to;
  555. } else {
  556. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  557. }
  558. }
  559. to++;
  560. }
  561. if (cLength > 0 && to < runes.Count && runes [to] != ' ' && runes [to] != '\t') {
  562. return from;
  563. } else if (cLength > 0 && to < runes.Count && (runes [to] == ' ' || runes [to] == '\t')) {
  564. return lastFrom;
  565. } else {
  566. return to;
  567. }
  568. }
  569. if (start < text.RuneCount) {
  570. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  571. }
  572. return lines;
  573. }
  574. /// <summary>
  575. /// Justifies text within a specified width.
  576. /// </summary>
  577. /// <param name="text">The text to justify.</param>
  578. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  579. /// <param name="talign">Alignment.</param>
  580. /// <param name="textDirection">The text direction.</param>
  581. /// <returns>Justified and clipped text.</returns>
  582. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  583. {
  584. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
  585. }
  586. /// <summary>
  587. /// Justifies text within a specified width.
  588. /// </summary>
  589. /// <param name="text">The text to justify.</param>
  590. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  591. /// <param name="justify">Justify.</param>
  592. /// <param name="textDirection">The text direction.</param>
  593. /// <returns>Justified and clipped text.</returns>
  594. public static ustring ClipAndJustify (ustring text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  595. {
  596. if (width < 0) {
  597. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  598. }
  599. if (ustring.IsNullOrEmpty (text)) {
  600. return text;
  601. }
  602. var runes = text.ToRuneList ();
  603. int slen = runes.Count;
  604. if (slen > width) {
  605. if (IsHorizontalDirection (textDirection)) {
  606. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  607. } else {
  608. return ustring.Make (runes.GetRange (0, width));
  609. }
  610. } else {
  611. if (justify) {
  612. return Justify (text, width, ' ', textDirection);
  613. } else if (IsHorizontalDirection (textDirection) && GetTextWidth (text) > width) {
  614. return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
  615. }
  616. return text;
  617. }
  618. }
  619. /// <summary>
  620. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  621. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  622. /// </summary>
  623. /// <param name="text"></param>
  624. /// <param name="width"></param>
  625. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  626. /// <param name="textDirection">The text direction.</param>
  627. /// <returns>The justified text.</returns>
  628. public static ustring Justify (ustring text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  629. {
  630. if (width < 0) {
  631. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  632. }
  633. if (ustring.IsNullOrEmpty (text)) {
  634. return text;
  635. }
  636. var words = text.Split (ustring.Make (' '));
  637. int textCount;
  638. if (IsHorizontalDirection (textDirection)) {
  639. textCount = words.Sum (arg => GetTextWidth (arg));
  640. } else {
  641. textCount = words.Sum (arg => arg.RuneCount);
  642. }
  643. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  644. var extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  645. var s = new System.Text.StringBuilder ();
  646. for (int w = 0; w < words.Length; w++) {
  647. var x = words [w];
  648. s.Append (x);
  649. if (w + 1 < words.Length)
  650. for (int i = 0; i < spaces; i++)
  651. s.Append (spaceChar);
  652. if (extras > 0) {
  653. for (int i = 0; i < 1; i++)
  654. s.Append (spaceChar);
  655. extras--;
  656. }
  657. if (w + 1 == words.Length - 1) {
  658. for (int i = 0; i < extras; i++)
  659. s.Append (spaceChar);
  660. }
  661. }
  662. return ustring.Make (s.ToString ());
  663. }
  664. static char [] whitespace = new char [] { ' ', '\t' };
  665. private int hotKeyPos;
  666. /// <summary>
  667. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  668. /// </summary>
  669. /// <param name="text"></param>
  670. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  671. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  672. /// <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>
  673. /// <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>
  674. /// <param name="tabWidth">The tab width.</param>
  675. /// <param name="textDirection">The text direction.</param>
  676. /// <returns>A list of word wrapped lines.</returns>
  677. /// <remarks>
  678. /// <para>
  679. /// An empty <c>text</c> string will result in one empty line.
  680. /// </para>
  681. /// <para>
  682. /// If <c>width</c> is 0, a single, empty line will be returned.
  683. /// </para>
  684. /// <para>
  685. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  686. /// </para>
  687. /// </remarks>
  688. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  689. {
  690. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  691. }
  692. /// <summary>
  693. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  694. /// </summary>
  695. /// <param name="text"></param>
  696. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  697. /// <param name="justify">Specifies whether the text should be justified.</param>
  698. /// <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>
  699. /// <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>
  700. /// <param name="tabWidth">The tab width.</param>
  701. /// <param name="textDirection">The text direction.</param>
  702. /// <returns>A list of word wrapped lines.</returns>
  703. /// <remarks>
  704. /// <para>
  705. /// An empty <c>text</c> string will result in one empty line.
  706. /// </para>
  707. /// <para>
  708. /// If <c>width</c> is 0, a single, empty line will be returned.
  709. /// </para>
  710. /// <para>
  711. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  712. /// </para>
  713. /// </remarks>
  714. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  715. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  716. {
  717. if (width < 0) {
  718. throw new ArgumentOutOfRangeException ("width cannot be negative");
  719. }
  720. List<ustring> lineResult = new List<ustring> ();
  721. if (ustring.IsNullOrEmpty (text) || width == 0) {
  722. lineResult.Add (ustring.Empty);
  723. return lineResult;
  724. }
  725. if (wordWrap == false) {
  726. text = ReplaceCRLFWithSpace (text);
  727. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  728. return lineResult;
  729. }
  730. var runes = StripCRLF (text, true).ToRuneList ();
  731. int runeCount = runes.Count;
  732. int lp = 0;
  733. for (int i = 0; i < runeCount; i++) {
  734. Rune c = runes [i];
  735. if (c == '\n') {
  736. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  737. foreach (var line in wrappedLines) {
  738. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  739. }
  740. if (wrappedLines.Count == 0) {
  741. lineResult.Add (ustring.Empty);
  742. }
  743. lp = i + 1;
  744. }
  745. }
  746. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  747. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  748. }
  749. return lineResult;
  750. }
  751. /// <summary>
  752. /// Computes the number of lines needed to render the specified text given the width.
  753. /// </summary>
  754. /// <returns>Number of lines.</returns>
  755. /// <param name="text">Text, may contain newlines.</param>
  756. /// <param name="width">The minimum width for the text.</param>
  757. public static int MaxLines (ustring text, int width)
  758. {
  759. var result = TextFormatter.Format (text, width, false, true);
  760. return result.Count;
  761. }
  762. /// <summary>
  763. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  764. /// </summary>
  765. /// <returns>Max width of lines.</returns>
  766. /// <param name="text">Text, may contain newlines.</param>
  767. /// <param name="width">The minimum width for the text.</param>
  768. public static int MaxWidth (ustring text, int width)
  769. {
  770. var result = TextFormatter.Format (text, width, false, true);
  771. var max = 0;
  772. result.ForEach (s => {
  773. var m = 0;
  774. s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
  775. if (m > max) {
  776. max = m;
  777. }
  778. });
  779. return max;
  780. }
  781. /// <summary>
  782. /// Determines the line with the highest width in the
  783. /// <paramref name="text"/> if it contains newlines.
  784. /// </summary>
  785. /// <param name="text">Text, may contain newlines.</param>
  786. /// <returns>The highest line width.</returns>
  787. public static int MaxWidthLine (ustring text)
  788. {
  789. var result = TextFormatter.SplitNewLine (text);
  790. return result.Max (x => x.ConsoleWidth);
  791. }
  792. /// <summary>
  793. /// Gets the total width of the passed text.
  794. /// </summary>
  795. /// <param name="text"></param>
  796. /// <returns>The text width.</returns>
  797. public static int GetTextWidth (ustring text)
  798. {
  799. return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
  800. }
  801. /// <summary>
  802. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  803. /// and the <paramref name="length"/>.
  804. /// </summary>
  805. /// <param name="lines">The lines.</param>
  806. /// <param name="startIndex">The start index.</param>
  807. /// <param name="length">The length.</param>
  808. /// <returns>The maximum characters width.</returns>
  809. public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
  810. {
  811. var max = 0;
  812. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  813. var runes = lines [i];
  814. if (runes.Length > 0)
  815. max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
  816. }
  817. return max;
  818. }
  819. /// <summary>
  820. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  821. /// and the <paramref name="length"/>.
  822. /// </summary>
  823. /// <param name="text">The text.</param>
  824. /// <param name="startIndex">The start index.</param>
  825. /// <param name="length">The length.</param>
  826. /// <returns>The maximum characters width.</returns>
  827. public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
  828. {
  829. var max = 0;
  830. var runes = text.ToRunes ();
  831. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  832. max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
  833. }
  834. return max;
  835. }
  836. /// <summary>
  837. /// Gets the index position from the text based on the <paramref name="width"/>.
  838. /// </summary>
  839. /// <param name="text">The text.</param>
  840. /// <param name="width">The width.</param>
  841. /// <returns>The index of the text that fit the width.</returns>
  842. public static int GetMaxLengthForWidth (ustring text, int width)
  843. {
  844. var runes = text.ToRuneList ();
  845. var runesLength = 0;
  846. var runeIdx = 0;
  847. for (; runeIdx < runes.Count; runeIdx++) {
  848. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  849. if (runesLength + runeWidth > width) {
  850. break;
  851. }
  852. runesLength += runeWidth;
  853. }
  854. return runeIdx;
  855. }
  856. /// <summary>
  857. /// Gets the index position from the list based on the <paramref name="width"/>.
  858. /// </summary>
  859. /// <param name="runes">The runes.</param>
  860. /// <param name="width">The width.</param>
  861. /// <returns>The index of the list that fit the width.</returns>
  862. public static int GetMaxLengthForWidth (List<Rune> runes, int width)
  863. {
  864. var runesLength = 0;
  865. var runeIdx = 0;
  866. for (; runeIdx < runes.Count; runeIdx++) {
  867. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  868. if (runesLength + runeWidth > width) {
  869. break;
  870. }
  871. runesLength += runeWidth;
  872. }
  873. return runeIdx;
  874. }
  875. /// <summary>
  876. /// Gets the index position from the list based on the <paramref name="width"/>.
  877. /// </summary>
  878. /// <param name="lines">The lines.</param>
  879. /// <param name="width">The width.</param>
  880. /// <returns>The index of the list that fit the width.</returns>
  881. public static int GetMaxColsForWidth (List<ustring> lines, int width)
  882. {
  883. var runesLength = 0;
  884. var lineIdx = 0;
  885. for (; lineIdx < lines.Count; lineIdx++) {
  886. var runes = lines [lineIdx].ToRuneList ();
  887. var maxRruneWidth = runes.Count > 0
  888. ? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
  889. if (runesLength + maxRruneWidth > width) {
  890. break;
  891. }
  892. runesLength += maxRruneWidth;
  893. }
  894. return lineIdx;
  895. }
  896. /// <summary>
  897. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  898. /// </summary>
  899. /// <param name="x">The x location of the rectangle</param>
  900. /// <param name="y">The y location of the rectangle</param>
  901. /// <param name="text">The text to measure</param>
  902. /// <param name="direction">The text direction.</param>
  903. /// <returns></returns>
  904. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  905. {
  906. if (ustring.IsNullOrEmpty (text)) {
  907. return new Rect (new Point (x, y), Size.Empty);
  908. }
  909. int w, h;
  910. if (IsHorizontalDirection (direction)) {
  911. int mw = 0;
  912. int ml = 1;
  913. int cols = 0;
  914. foreach (var rune in text) {
  915. if (rune == '\n') {
  916. ml++;
  917. if (cols > mw) {
  918. mw = cols;
  919. }
  920. cols = 0;
  921. } else if (rune != '\r') {
  922. cols++;
  923. var rw = Rune.ColumnWidth (rune);
  924. if (rw > 0) {
  925. rw--;
  926. }
  927. cols += rw;
  928. }
  929. }
  930. if (cols > mw) {
  931. mw = cols;
  932. }
  933. w = mw;
  934. h = ml;
  935. } else {
  936. int vw = 1, cw = 1;
  937. int vh = 0;
  938. int rows = 0;
  939. foreach (var rune in text) {
  940. if (rune == '\n') {
  941. vw++;
  942. if (rows > vh) {
  943. vh = rows;
  944. }
  945. rows = 0;
  946. cw = 1;
  947. } else if (rune != '\r') {
  948. rows++;
  949. var rw = Rune.ColumnWidth (rune);
  950. if (cw < rw) {
  951. cw = rw;
  952. vw++;
  953. }
  954. }
  955. }
  956. if (rows > vh) {
  957. vh = rows;
  958. }
  959. w = vw;
  960. h = vh;
  961. }
  962. return new Rect (x, y, w, h);
  963. }
  964. /// <summary>
  965. /// Finds the hotkey and its location in text.
  966. /// </summary>
  967. /// <param name="text">The text to look in.</param>
  968. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  969. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  970. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  971. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  972. /// <param name="hotKey">Outputs the hotKey.</param>
  973. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  974. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  975. {
  976. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  977. hotPos = -1;
  978. hotKey = Key.Unknown;
  979. return false;
  980. }
  981. Rune hot_key = (Rune)0;
  982. int hot_pos = -1;
  983. // Use first hot_key char passed into 'hotKey'.
  984. // TODO: Ignore hot_key of two are provided
  985. // TODO: Do not support non-alphanumeric chars that can't be typed
  986. int i = 0;
  987. foreach (Rune c in text) {
  988. if ((char)c != 0xFFFD) {
  989. if (c == hotKeySpecifier) {
  990. hot_pos = i;
  991. } else if (hot_pos > -1) {
  992. hot_key = c;
  993. break;
  994. }
  995. }
  996. i++;
  997. }
  998. // Legacy support - use first upper case char if the specifier was not found
  999. if (hot_pos == -1 && firstUpperCase) {
  1000. i = 0;
  1001. foreach (Rune c in text) {
  1002. if ((char)c != 0xFFFD) {
  1003. if (Rune.IsUpper (c)) {
  1004. hot_key = c;
  1005. hot_pos = i;
  1006. break;
  1007. }
  1008. }
  1009. i++;
  1010. }
  1011. }
  1012. if (hot_key != (Rune)0 && hot_pos != -1) {
  1013. hotPos = hot_pos;
  1014. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  1015. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  1016. return true;
  1017. }
  1018. }
  1019. hotPos = -1;
  1020. hotKey = Key.Unknown;
  1021. return false;
  1022. }
  1023. /// <summary>
  1024. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  1025. /// it as the hotkey.
  1026. /// </summary>
  1027. /// <param name="text">The text to tag the hotkey in.</param>
  1028. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1029. /// <returns>The text with the hotkey tagged.</returns>
  1030. /// <remarks>
  1031. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  1032. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  1033. /// </remarks>
  1034. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  1035. {
  1036. // Set the high bit
  1037. var runes = text.ToRuneList ();
  1038. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  1039. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  1040. }
  1041. return ustring.Make (runes);
  1042. }
  1043. /// <summary>
  1044. /// Removes the hotkey specifier from text.
  1045. /// </summary>
  1046. /// <param name="text">The text to manipulate.</param>
  1047. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1048. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1049. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1050. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  1051. {
  1052. if (ustring.IsNullOrEmpty (text)) {
  1053. return text;
  1054. }
  1055. // Scan
  1056. ustring start = ustring.Empty;
  1057. int i = 0;
  1058. foreach (Rune c in text) {
  1059. if (c == hotKeySpecifier && i == hotPos) {
  1060. i++;
  1061. continue;
  1062. }
  1063. start += ustring.Make (c);
  1064. i++;
  1065. }
  1066. return start;
  1067. }
  1068. /// <summary>
  1069. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  1070. /// </summary>
  1071. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1072. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1073. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1074. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1075. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default)
  1076. {
  1077. // With this check, we protect against subclasses with overrides of Text (like Button)
  1078. if (ustring.IsNullOrEmpty (text)) {
  1079. return;
  1080. }
  1081. Application.Driver?.SetAttribute (normalColor);
  1082. // Use "Lines" to ensure a Format (don't use "lines"))
  1083. var linesFormated = Lines;
  1084. switch (textDirection) {
  1085. case TextDirection.TopBottom_RightLeft:
  1086. case TextDirection.LeftRight_BottomTop:
  1087. case TextDirection.RightLeft_BottomTop:
  1088. case TextDirection.BottomTop_RightLeft:
  1089. linesFormated.Reverse ();
  1090. break;
  1091. }
  1092. var isVertical = IsVerticalDirection (textDirection);
  1093. for (int line = 0; line < linesFormated.Count; line++) {
  1094. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1095. continue;
  1096. var runes = lines [line].ToRunes ();
  1097. switch (textDirection) {
  1098. case TextDirection.RightLeft_BottomTop:
  1099. case TextDirection.RightLeft_TopBottom:
  1100. case TextDirection.BottomTop_LeftRight:
  1101. case TextDirection.BottomTop_RightLeft:
  1102. runes = runes.Reverse ().ToArray ();
  1103. break;
  1104. }
  1105. // When text is justified, we lost left or right, so we use the direction to align.
  1106. int x, y;
  1107. // Horizontal Alignment
  1108. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  1109. if (isVertical) {
  1110. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1111. x = bounds.Right - runesWidth;
  1112. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1113. } else {
  1114. var runesWidth = GetTextWidth (ustring.Make (runes));
  1115. x = bounds.Right - runesWidth;
  1116. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1117. }
  1118. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  1119. if (isVertical) {
  1120. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line) : 0;
  1121. x = bounds.Left + runesWidth;
  1122. } else {
  1123. x = bounds.Left;
  1124. }
  1125. CursorPosition = hotKeyPos;
  1126. } else if (textAlignment == TextAlignment.Centered) {
  1127. if (isVertical) {
  1128. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1129. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1130. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1131. } else {
  1132. var runesWidth = GetTextWidth (ustring.Make (runes));
  1133. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1134. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1135. }
  1136. } else {
  1137. throw new ArgumentOutOfRangeException ();
  1138. }
  1139. // Vertical Alignment
  1140. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  1141. if (isVertical) {
  1142. y = bounds.Bottom - runes.Length;
  1143. } else {
  1144. y = bounds.Bottom - Lines.Count + line;
  1145. }
  1146. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  1147. if (isVertical) {
  1148. y = bounds.Top;
  1149. } else {
  1150. y = bounds.Top + line;
  1151. }
  1152. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  1153. if (isVertical) {
  1154. var s = (bounds.Height - runes.Length) / 2;
  1155. y = bounds.Top + s;
  1156. } else {
  1157. var s = (bounds.Height - Lines.Count) / 2;
  1158. y = bounds.Top + line + s;
  1159. }
  1160. } else {
  1161. throw new ArgumentOutOfRangeException ();
  1162. }
  1163. var start = isVertical ? bounds.Top : bounds.Left;
  1164. var size = isVertical ? bounds.Height : bounds.Width;
  1165. var current = start;
  1166. var savedClip = Application.Driver?.Clip;
  1167. if (Application.Driver != null && containerBounds != default) {
  1168. Application.Driver.Clip = containerBounds == default
  1169. ? bounds
  1170. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1171. Math.Max (containerBounds.Y, bounds.Y),
  1172. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1173. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1174. }
  1175. for (var idx = (isVertical ? start - y : start - x); current < start + size; idx++) {
  1176. if (idx < 0) {
  1177. current++;
  1178. continue;
  1179. } else if (idx > runes.Length - 1) {
  1180. break;
  1181. }
  1182. var rune = (Rune)' ';
  1183. if (isVertical) {
  1184. Application.Driver?.Move (x, current);
  1185. if (idx >= 0 && idx < runes.Length) {
  1186. rune = runes [idx];
  1187. }
  1188. } else {
  1189. Application.Driver?.Move (current, y);
  1190. if (idx >= 0 && idx < runes.Length) {
  1191. rune = runes [idx];
  1192. }
  1193. }
  1194. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  1195. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1196. (!isVertical && textAlignment == TextAlignment.Justified)) {
  1197. CursorPosition = idx - start;
  1198. }
  1199. Application.Driver?.SetAttribute (hotColor);
  1200. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  1201. Application.Driver?.SetAttribute (normalColor);
  1202. } else {
  1203. Application.Driver?.AddRune (rune);
  1204. }
  1205. var runeWidth = Math.Max (Rune.ColumnWidth (rune), 1);
  1206. if (isVertical) {
  1207. current++;
  1208. } else {
  1209. current += runeWidth;
  1210. }
  1211. if (!isVertical && idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > start + size) {
  1212. break;
  1213. }
  1214. }
  1215. if (Application.Driver != null)
  1216. Application.Driver.Clip = (Rect)savedClip;
  1217. }
  1218. }
  1219. }
  1220. }