TextFormatter.cs 39 KB

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