TextFormatter.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  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 : 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. extras--;
  654. }
  655. }
  656. return ustring.Make (s.ToString ());
  657. }
  658. static char [] whitespace = new char [] { ' ', '\t' };
  659. private int hotKeyPos;
  660. /// <summary>
  661. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  662. /// </summary>
  663. /// <param name="text"></param>
  664. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  665. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  666. /// <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>
  667. /// <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>
  668. /// <param name="tabWidth">The tab width.</param>
  669. /// <param name="textDirection">The text direction.</param>
  670. /// <returns>A list of word wrapped lines.</returns>
  671. /// <remarks>
  672. /// <para>
  673. /// An empty <c>text</c> string will result in one empty line.
  674. /// </para>
  675. /// <para>
  676. /// If <c>width</c> is 0, a single, empty line will be returned.
  677. /// </para>
  678. /// <para>
  679. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  680. /// </para>
  681. /// </remarks>
  682. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  683. {
  684. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  685. }
  686. /// <summary>
  687. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  688. /// </summary>
  689. /// <param name="text"></param>
  690. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  691. /// <param name="justify">Specifies whether the text should be justified.</param>
  692. /// <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>
  693. /// <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>
  694. /// <param name="tabWidth">The tab width.</param>
  695. /// <param name="textDirection">The text direction.</param>
  696. /// <returns>A list of word wrapped lines.</returns>
  697. /// <remarks>
  698. /// <para>
  699. /// An empty <c>text</c> string will result in one empty line.
  700. /// </para>
  701. /// <para>
  702. /// If <c>width</c> is 0, a single, empty line will be returned.
  703. /// </para>
  704. /// <para>
  705. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  706. /// </para>
  707. /// </remarks>
  708. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  709. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  710. {
  711. if (width < 0) {
  712. throw new ArgumentOutOfRangeException ("width cannot be negative");
  713. }
  714. List<ustring> lineResult = new List<ustring> ();
  715. if (ustring.IsNullOrEmpty (text) || width == 0) {
  716. lineResult.Add (ustring.Empty);
  717. return lineResult;
  718. }
  719. if (wordWrap == false) {
  720. text = ReplaceCRLFWithSpace (text);
  721. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  722. return lineResult;
  723. }
  724. var runes = StripCRLF (text, true).ToRuneList ();
  725. int runeCount = runes.Count;
  726. int lp = 0;
  727. for (int i = 0; i < runeCount; i++) {
  728. Rune c = runes [i];
  729. if (c == '\n') {
  730. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  731. foreach (var line in wrappedLines) {
  732. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  733. }
  734. if (wrappedLines.Count == 0) {
  735. lineResult.Add (ustring.Empty);
  736. }
  737. lp = i + 1;
  738. }
  739. }
  740. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  741. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  742. }
  743. return lineResult;
  744. }
  745. /// <summary>
  746. /// Computes the number of lines needed to render the specified text given the width.
  747. /// </summary>
  748. /// <returns>Number of lines.</returns>
  749. /// <param name="text">Text, may contain newlines.</param>
  750. /// <param name="width">The minimum width for the text.</param>
  751. public static int MaxLines (ustring text, int width)
  752. {
  753. var result = TextFormatter.Format (text, width, false, true);
  754. return result.Count;
  755. }
  756. /// <summary>
  757. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  758. /// </summary>
  759. /// <returns>Max width of lines.</returns>
  760. /// <param name="text">Text, may contain newlines.</param>
  761. /// <param name="width">The minimum width for the text.</param>
  762. public static int MaxWidth (ustring text, int width)
  763. {
  764. var result = TextFormatter.Format (text, width, false, true);
  765. var max = 0;
  766. result.ForEach (s => {
  767. var m = 0;
  768. s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
  769. if (m > max) {
  770. max = m;
  771. }
  772. });
  773. return max;
  774. }
  775. /// <summary>
  776. /// Gets the total width of the passed text.
  777. /// </summary>
  778. /// <param name="text"></param>
  779. /// <returns>The text width.</returns>
  780. public static int GetTextWidth (ustring text)
  781. {
  782. return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
  783. }
  784. /// <summary>
  785. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  786. /// and the <paramref name="length"/>.
  787. /// </summary>
  788. /// <param name="lines">The lines.</param>
  789. /// <param name="startIndex">The start index.</param>
  790. /// <param name="length">The length.</param>
  791. /// <returns>The maximum characters width.</returns>
  792. public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
  793. {
  794. var max = 0;
  795. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  796. var runes = lines [i];
  797. if (runes.Length > 0)
  798. max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
  799. }
  800. return max;
  801. }
  802. /// <summary>
  803. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  804. /// and the <paramref name="length"/>.
  805. /// </summary>
  806. /// <param name="text">The text.</param>
  807. /// <param name="startIndex">The start index.</param>
  808. /// <param name="length">The length.</param>
  809. /// <returns>The maximum characters width.</returns>
  810. public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
  811. {
  812. var max = 0;
  813. var runes = text.ToRunes ();
  814. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  815. max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
  816. }
  817. return max;
  818. }
  819. /// <summary>
  820. /// Gets the index position from the text based on the <paramref name="width"/>.
  821. /// </summary>
  822. /// <param name="text">The text.</param>
  823. /// <param name="width">The width.</param>
  824. /// <returns>The index of the text that fit the width.</returns>
  825. public static int GetMaxLengthForWidth (ustring text, int width)
  826. {
  827. var runes = text.ToRuneList ();
  828. var runesLength = 0;
  829. var runeIdx = 0;
  830. for (; runeIdx < runes.Count; runeIdx++) {
  831. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  832. if (runesLength + runeWidth > width) {
  833. break;
  834. }
  835. runesLength += runeWidth;
  836. }
  837. return runeIdx;
  838. }
  839. /// <summary>
  840. /// Gets the index position from the list based on the <paramref name="width"/>.
  841. /// </summary>
  842. /// <param name="runes">The runes.</param>
  843. /// <param name="width">The width.</param>
  844. /// <returns>The index of the list that fit the width.</returns>
  845. public static int GetMaxLengthForWidth (List<Rune> runes, int width)
  846. {
  847. var runesLength = 0;
  848. var runeIdx = 0;
  849. for (; runeIdx < runes.Count; runeIdx++) {
  850. var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
  851. if (runesLength + runeWidth > width) {
  852. break;
  853. }
  854. runesLength += runeWidth;
  855. }
  856. return runeIdx;
  857. }
  858. /// <summary>
  859. /// Gets the index position from the list based on the <paramref name="width"/>.
  860. /// </summary>
  861. /// <param name="lines">The lines.</param>
  862. /// <param name="width">The width.</param>
  863. /// <returns>The index of the list that fit the width.</returns>
  864. public static int GetMaxColsForWidth (List<ustring> lines, int width)
  865. {
  866. var runesLength = 0;
  867. var lineIdx = 0;
  868. for (; lineIdx < lines.Count; lineIdx++) {
  869. var runes = lines [lineIdx].ToRuneList ();
  870. var maxRruneWidth = runes.Count > 0
  871. ? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
  872. if (runesLength + maxRruneWidth > width) {
  873. break;
  874. }
  875. runesLength += maxRruneWidth;
  876. }
  877. return lineIdx;
  878. }
  879. /// <summary>
  880. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  881. /// </summary>
  882. /// <param name="x">The x location of the rectangle</param>
  883. /// <param name="y">The y location of the rectangle</param>
  884. /// <param name="text">The text to measure</param>
  885. /// <param name="direction">The text direction.</param>
  886. /// <returns></returns>
  887. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  888. {
  889. if (ustring.IsNullOrEmpty (text)) {
  890. return new Rect (new Point (x, y), Size.Empty);
  891. }
  892. int w, h;
  893. if (IsHorizontalDirection (direction)) {
  894. int mw = 0;
  895. int ml = 1;
  896. int cols = 0;
  897. foreach (var rune in text) {
  898. if (rune == '\n') {
  899. ml++;
  900. if (cols > mw) {
  901. mw = cols;
  902. }
  903. cols = 0;
  904. } else if (rune != '\r') {
  905. cols++;
  906. var rw = Rune.ColumnWidth (rune);
  907. if (rw > 0) {
  908. rw--;
  909. }
  910. cols += rw;
  911. }
  912. }
  913. if (cols > mw) {
  914. mw = cols;
  915. }
  916. w = mw;
  917. h = ml;
  918. } else {
  919. int vw = 1, cw = 1;
  920. int vh = 0;
  921. int rows = 0;
  922. foreach (var rune in text) {
  923. if (rune == '\n') {
  924. vw++;
  925. if (rows > vh) {
  926. vh = rows;
  927. }
  928. rows = 0;
  929. cw = 1;
  930. } else if (rune != '\r') {
  931. rows++;
  932. var rw = Rune.ColumnWidth (rune);
  933. if (cw < rw) {
  934. cw = rw;
  935. vw++;
  936. }
  937. }
  938. }
  939. if (rows > vh) {
  940. vh = rows;
  941. }
  942. w = vw;
  943. h = vh;
  944. }
  945. return new Rect (x, y, w, h);
  946. }
  947. /// <summary>
  948. /// Finds the hotkey and its location in text.
  949. /// </summary>
  950. /// <param name="text">The text to look in.</param>
  951. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  952. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  953. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  954. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  955. /// <param name="hotKey">Outputs the hotKey.</param>
  956. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  957. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  958. {
  959. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  960. hotPos = -1;
  961. hotKey = Key.Unknown;
  962. return false;
  963. }
  964. Rune hot_key = (Rune)0;
  965. int hot_pos = -1;
  966. // Use first hot_key char passed into 'hotKey'.
  967. // TODO: Ignore hot_key of two are provided
  968. // TODO: Do not support non-alphanumeric chars that can't be typed
  969. int i = 0;
  970. foreach (Rune c in text) {
  971. if ((char)c != 0xFFFD) {
  972. if (c == hotKeySpecifier) {
  973. hot_pos = i;
  974. } else if (hot_pos > -1) {
  975. hot_key = c;
  976. break;
  977. }
  978. }
  979. i++;
  980. }
  981. // Legacy support - use first upper case char if the specifier was not found
  982. if (hot_pos == -1 && firstUpperCase) {
  983. i = 0;
  984. foreach (Rune c in text) {
  985. if ((char)c != 0xFFFD) {
  986. if (Rune.IsUpper (c)) {
  987. hot_key = c;
  988. hot_pos = i;
  989. break;
  990. }
  991. }
  992. i++;
  993. }
  994. }
  995. if (hot_key != (Rune)0 && hot_pos != -1) {
  996. hotPos = hot_pos;
  997. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  998. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  999. return true;
  1000. }
  1001. }
  1002. hotPos = -1;
  1003. hotKey = Key.Unknown;
  1004. return false;
  1005. }
  1006. /// <summary>
  1007. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  1008. /// it as the hotkey.
  1009. /// </summary>
  1010. /// <param name="text">The text to tag the hotkey in.</param>
  1011. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1012. /// <returns>The text with the hotkey tagged.</returns>
  1013. /// <remarks>
  1014. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  1015. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  1016. /// </remarks>
  1017. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  1018. {
  1019. // Set the high bit
  1020. var runes = text.ToRuneList ();
  1021. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  1022. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  1023. }
  1024. return ustring.Make (runes);
  1025. }
  1026. /// <summary>
  1027. /// Removes the hotkey specifier from text.
  1028. /// </summary>
  1029. /// <param name="text">The text to manipulate.</param>
  1030. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1031. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1032. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1033. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  1034. {
  1035. if (ustring.IsNullOrEmpty (text)) {
  1036. return text;
  1037. }
  1038. // Scan
  1039. ustring start = ustring.Empty;
  1040. int i = 0;
  1041. foreach (Rune c in text) {
  1042. if (c == hotKeySpecifier && i == hotPos) {
  1043. i++;
  1044. continue;
  1045. }
  1046. start += ustring.Make (c);
  1047. i++;
  1048. }
  1049. return start;
  1050. }
  1051. /// <summary>
  1052. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  1053. /// </summary>
  1054. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1055. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1056. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1057. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1058. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default)
  1059. {
  1060. // With this check, we protect against subclasses with overrides of Text (like Button)
  1061. if (ustring.IsNullOrEmpty (text)) {
  1062. return;
  1063. }
  1064. Application.Driver?.SetAttribute (normalColor);
  1065. // Use "Lines" to ensure a Format (don't use "lines"))
  1066. var linesFormated = Lines;
  1067. switch (textDirection) {
  1068. case TextDirection.TopBottom_RightLeft:
  1069. case TextDirection.LeftRight_BottomTop:
  1070. case TextDirection.RightLeft_BottomTop:
  1071. case TextDirection.BottomTop_RightLeft:
  1072. linesFormated.Reverse ();
  1073. break;
  1074. }
  1075. var isVertical = IsVerticalDirection (textDirection);
  1076. for (int line = 0; line < linesFormated.Count; line++) {
  1077. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1078. continue;
  1079. var runes = lines [line].ToRunes ();
  1080. switch (textDirection) {
  1081. case TextDirection.RightLeft_BottomTop:
  1082. case TextDirection.RightLeft_TopBottom:
  1083. case TextDirection.BottomTop_LeftRight:
  1084. case TextDirection.BottomTop_RightLeft:
  1085. runes = runes.Reverse ().ToArray ();
  1086. break;
  1087. }
  1088. // When text is justified, we lost left or right, so we use the direction to align.
  1089. int x, y;
  1090. // Horizontal Alignment
  1091. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  1092. if (isVertical) {
  1093. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1094. x = bounds.Right - runesWidth;
  1095. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1096. } else {
  1097. var runesWidth = GetTextWidth (ustring.Make (runes));
  1098. x = bounds.Right - runesWidth;
  1099. CursorPosition = bounds.Width - runesWidth + hotKeyPos;
  1100. }
  1101. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  1102. if (isVertical) {
  1103. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line) : 0;
  1104. x = bounds.Left + runesWidth;
  1105. } else {
  1106. x = bounds.Left;
  1107. }
  1108. CursorPosition = hotKeyPos;
  1109. } else if (textAlignment == TextAlignment.Centered) {
  1110. if (isVertical) {
  1111. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1112. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1113. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1114. } else {
  1115. var runesWidth = GetTextWidth (ustring.Make (runes));
  1116. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1117. CursorPosition = (bounds.Width - runesWidth) / 2 + hotKeyPos;
  1118. }
  1119. } else {
  1120. throw new ArgumentOutOfRangeException ();
  1121. }
  1122. // Vertical Alignment
  1123. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  1124. if (isVertical) {
  1125. y = bounds.Bottom - runes.Length;
  1126. } else {
  1127. y = bounds.Bottom - Lines.Count + line;
  1128. }
  1129. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  1130. if (isVertical) {
  1131. y = bounds.Top;
  1132. } else {
  1133. y = bounds.Top + line;
  1134. }
  1135. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  1136. if (isVertical) {
  1137. var s = (bounds.Height - runes.Length) / 2;
  1138. y = bounds.Top + s;
  1139. } else {
  1140. var s = (bounds.Height - Lines.Count) / 2;
  1141. y = bounds.Top + line + s;
  1142. }
  1143. } else {
  1144. throw new ArgumentOutOfRangeException ();
  1145. }
  1146. var start = isVertical ? bounds.Top : bounds.Left;
  1147. var size = isVertical ? bounds.Height : bounds.Width;
  1148. var current = start;
  1149. var savedClip = Application.Driver?.Clip;
  1150. if (Application.Driver != null && containerBounds != default) {
  1151. Application.Driver.Clip = containerBounds == default
  1152. ? bounds
  1153. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1154. Math.Max (containerBounds.Y, bounds.Y),
  1155. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1156. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1157. }
  1158. for (var idx = (isVertical ? start - y : start - x); current < start + size; idx++) {
  1159. if (idx < 0) {
  1160. current++;
  1161. continue;
  1162. } else if (idx > runes.Length - 1) {
  1163. break;
  1164. }
  1165. var rune = (Rune)' ';
  1166. if (isVertical) {
  1167. Application.Driver?.Move (x, current);
  1168. if (idx >= 0 && idx < runes.Length) {
  1169. rune = runes [idx];
  1170. }
  1171. } else {
  1172. Application.Driver?.Move (current, y);
  1173. if (idx >= 0 && idx < runes.Length) {
  1174. rune = runes [idx];
  1175. }
  1176. }
  1177. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  1178. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1179. (!isVertical && textAlignment == TextAlignment.Justified)) {
  1180. CursorPosition = idx - start;
  1181. }
  1182. Application.Driver?.SetAttribute (hotColor);
  1183. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  1184. Application.Driver?.SetAttribute (normalColor);
  1185. } else {
  1186. Application.Driver?.AddRune (rune);
  1187. }
  1188. var runeWidth = Math.Max (Rune.ColumnWidth (rune), 1);
  1189. if (isVertical) {
  1190. current++;
  1191. } else {
  1192. current += runeWidth;
  1193. }
  1194. if (!isVertical && idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > start + size) {
  1195. break;
  1196. }
  1197. }
  1198. if (Application.Driver != null)
  1199. Application.Driver.Clip = (Rect)savedClip;
  1200. }
  1201. }
  1202. }
  1203. }