TextFormatter.cs 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Provides text formatting. Supports <see cref="View.HotKey"/>s, horizontal and vertical alignment, text direction,
  6. /// multiple lines, and word-based line wrap.
  7. /// </summary>
  8. public class TextFormatter
  9. {
  10. private Key _hotKey = new ();
  11. private int _hotKeyPos = -1;
  12. private List<string> _lines = new ();
  13. private bool _multiLine;
  14. private bool _preserveTrailingSpaces;
  15. private int _tabWidth = 4;
  16. private string? _text;
  17. private Alignment _textAlignment = Alignment.Start;
  18. private TextDirection _textDirection;
  19. private Alignment _textVerticalAlignment = Alignment.Start;
  20. private bool _wordWrap = true;
  21. /// <summary>Get or sets the horizontal text alignment.</summary>
  22. /// <value>The text alignment.</value>
  23. public Alignment Alignment
  24. {
  25. get => _textAlignment;
  26. set => _textAlignment = EnableNeedsFormat (value);
  27. }
  28. /// <summary>
  29. /// Gets the cursor position of the <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will
  30. /// be positioned over it.
  31. /// </summary>
  32. public int CursorPosition { get; internal set; }
  33. /// <summary>Gets or sets the text-direction.</summary>
  34. /// <value>The text direction.</value>
  35. public TextDirection Direction
  36. {
  37. get => _textDirection;
  38. set => _textDirection = EnableNeedsFormat (value);
  39. }
  40. /// <summary>Draws the text held by <see cref="TextFormatter"/> to <see cref="ConsoleDriver"/> using the colors specified.</summary>
  41. /// <remarks>
  42. /// Causes the text to be formatted (references <see cref="GetLines"/>). Sets <see cref="NeedsFormat"/> to
  43. /// <c>false</c>.
  44. /// </remarks>
  45. /// <param name="screen">Specifies the screen-relative location and maximum size for drawing the text.</param>
  46. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  47. /// <param name="hotColor">The color to use to draw the hotkey</param>
  48. /// <param name="maximum">Specifies the screen-relative location and maximum container size.</param>
  49. /// <param name="driver">The console driver currently used by the application.</param>
  50. /// <exception cref="ArgumentOutOfRangeException"></exception>
  51. public void Draw (
  52. Rectangle screen,
  53. Attribute normalColor,
  54. Attribute hotColor,
  55. Rectangle maximum = default,
  56. ConsoleDriver? driver = null
  57. )
  58. {
  59. // With this check, we protect against subclasses with overrides of Text (like Button)
  60. if (string.IsNullOrEmpty (Text))
  61. {
  62. return;
  63. }
  64. driver ??= Application.Driver;
  65. driver?.SetAttribute (normalColor);
  66. List<string> linesFormatted = GetLines ();
  67. bool isVertical = IsVerticalDirection (Direction);
  68. Rectangle maxScreen = screen;
  69. if (driver is { })
  70. {
  71. // INTENT: What, exactly, is the intent of this?
  72. maxScreen = maximum == default (Rectangle)
  73. ? screen
  74. : new (
  75. Math.Max (maximum.X, screen.X),
  76. Math.Max (maximum.Y, screen.Y),
  77. Math.Max (
  78. Math.Min (maximum.Width, maximum.Right - screen.Left),
  79. 0
  80. ),
  81. Math.Max (
  82. Math.Min (
  83. maximum.Height,
  84. maximum.Bottom - screen.Top
  85. ),
  86. 0
  87. )
  88. );
  89. }
  90. if (maxScreen.Width == 0 || maxScreen.Height == 0)
  91. {
  92. return;
  93. }
  94. int lineOffset = !isVertical && screen.Y < 0 ? Math.Abs (screen.Y) : 0;
  95. for (int line = lineOffset; line < linesFormatted.Count; line++)
  96. {
  97. if ((isVertical && line > screen.Width) || (!isVertical && line > screen.Height))
  98. {
  99. continue;
  100. }
  101. if ((isVertical && line >= maxScreen.Left + maxScreen.Width)
  102. || (!isVertical && line >= maxScreen.Top + maxScreen.Height + lineOffset))
  103. {
  104. break;
  105. }
  106. Rune [] runes = linesFormatted [line].ToRunes ();
  107. // When text is justified, we lost left or right, so we use the direction to align.
  108. int x = 0, y = 0;
  109. // Horizontal Alignment
  110. if (Alignment is Alignment.End)
  111. {
  112. if (isVertical)
  113. {
  114. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, line, linesFormatted.Count - line, TabWidth);
  115. x = screen.Right - runesWidth;
  116. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  117. }
  118. else
  119. {
  120. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  121. x = screen.Right - runesWidth;
  122. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  123. }
  124. }
  125. else if (Alignment is Alignment.Start)
  126. {
  127. if (isVertical)
  128. {
  129. int runesWidth = line > 0
  130. ? GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth)
  131. : 0;
  132. x = screen.Left + runesWidth;
  133. }
  134. else
  135. {
  136. x = screen.Left;
  137. }
  138. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  139. }
  140. else if (Alignment is Alignment.Fill)
  141. {
  142. if (isVertical)
  143. {
  144. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  145. int prevLineWidth = line > 0 ? GetColumnsRequiredForVerticalText (linesFormatted, line - 1, 1, TabWidth) : 0;
  146. int firstLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, 1, TabWidth);
  147. int lastLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, linesFormatted.Count - 1, 1, TabWidth);
  148. var interval = (int)Math.Round ((double)(screen.Width + firstLineWidth + lastLineWidth) / linesFormatted.Count);
  149. x = line == 0
  150. ? screen.Left
  151. : line < linesFormatted.Count - 1
  152. ? screen.Width - runesWidth <= lastLineWidth ? screen.Left + prevLineWidth : screen.Left + line * interval
  153. : screen.Right - lastLineWidth;
  154. }
  155. else
  156. {
  157. x = screen.Left;
  158. }
  159. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  160. }
  161. else if (Alignment is Alignment.Center)
  162. {
  163. if (isVertical)
  164. {
  165. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  166. int linesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth);
  167. x = screen.Left + linesWidth + (screen.Width - runesWidth) / 2;
  168. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  169. }
  170. else
  171. {
  172. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  173. x = screen.Left + (screen.Width - runesWidth) / 2;
  174. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  175. }
  176. }
  177. else
  178. {
  179. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  180. return;
  181. }
  182. // Vertical Alignment
  183. if (VerticalAlignment is Alignment.End)
  184. {
  185. if (isVertical)
  186. {
  187. y = screen.Bottom - runes.Length;
  188. }
  189. else
  190. {
  191. y = screen.Bottom - linesFormatted.Count + line;
  192. }
  193. }
  194. else if (VerticalAlignment is Alignment.Start)
  195. {
  196. if (isVertical)
  197. {
  198. y = screen.Top;
  199. }
  200. else
  201. {
  202. y = screen.Top + line;
  203. }
  204. }
  205. else if (VerticalAlignment is Alignment.Fill)
  206. {
  207. if (isVertical)
  208. {
  209. y = screen.Top;
  210. }
  211. else
  212. {
  213. var interval = (int)Math.Round ((double)(screen.Height + 2) / linesFormatted.Count);
  214. y = line == 0 ? screen.Top :
  215. line < linesFormatted.Count - 1 ? screen.Height - interval <= 1 ? screen.Top + 1 : screen.Top + line * interval : screen.Bottom - 1;
  216. }
  217. }
  218. else if (VerticalAlignment is Alignment.Center)
  219. {
  220. if (isVertical)
  221. {
  222. int s = (screen.Height - runes.Length) / 2;
  223. y = screen.Top + s;
  224. }
  225. else
  226. {
  227. int s = (screen.Height - linesFormatted.Count) / 2;
  228. y = screen.Top + line + s;
  229. }
  230. }
  231. else
  232. {
  233. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  234. return;
  235. }
  236. int colOffset = screen.X < 0 ? Math.Abs (screen.X) : 0;
  237. int start = isVertical ? screen.Top : screen.Left;
  238. int size = isVertical ? screen.Height : screen.Width;
  239. int current = start + colOffset;
  240. List<Point?> lastZeroWidthPos = null!;
  241. Rune rune = default;
  242. int zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  243. for (int idx = (isVertical ? start - y : start - x) + colOffset;
  244. current < start + size + zeroLengthCount;
  245. idx++)
  246. {
  247. Rune lastRuneUsed = rune;
  248. if (lastZeroWidthPos is null)
  249. {
  250. if (idx < 0
  251. || (isVertical
  252. ? VerticalAlignment != Alignment.End && current < 0
  253. : Alignment != Alignment.End && x + current + colOffset < 0))
  254. {
  255. current++;
  256. continue;
  257. }
  258. if (!FillRemaining && idx > runes.Length - 1)
  259. {
  260. break;
  261. }
  262. if ((!isVertical
  263. && (current - start > maxScreen.Left + maxScreen.Width - screen.X + colOffset
  264. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width)))
  265. || (isVertical
  266. && ((current > start + size + zeroLengthCount && idx > maxScreen.Top + maxScreen.Height - screen.Y)
  267. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width))))
  268. {
  269. break;
  270. }
  271. }
  272. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - viewport.X + colOffset)
  273. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - viewport.Y))
  274. // break;
  275. rune = (Rune)' ';
  276. if (isVertical)
  277. {
  278. if (idx >= 0 && idx < runes.Length)
  279. {
  280. rune = runes [idx];
  281. }
  282. if (lastZeroWidthPos is null)
  283. {
  284. driver?.Move (x, current);
  285. }
  286. else
  287. {
  288. int foundIdx = lastZeroWidthPos.IndexOf (
  289. p =>
  290. p is { } && p.Value.Y == current
  291. );
  292. if (foundIdx > -1)
  293. {
  294. if (rune.IsCombiningMark ())
  295. {
  296. lastZeroWidthPos [foundIdx] =
  297. new Point (
  298. lastZeroWidthPos [foundIdx]!.Value.X + 1,
  299. current
  300. );
  301. driver?.Move (
  302. lastZeroWidthPos [foundIdx]!.Value.X,
  303. current
  304. );
  305. }
  306. else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ())
  307. {
  308. current++;
  309. driver?.Move (x, current);
  310. }
  311. else
  312. {
  313. driver?.Move (x, current);
  314. }
  315. }
  316. else
  317. {
  318. driver?.Move (x, current);
  319. }
  320. }
  321. }
  322. else
  323. {
  324. driver?.Move (current, y);
  325. if (idx >= 0 && idx < runes.Length)
  326. {
  327. rune = runes [idx];
  328. }
  329. }
  330. int runeWidth = GetRuneWidth (rune, TabWidth);
  331. if (HotKeyPos > -1 && idx == HotKeyPos)
  332. {
  333. if ((isVertical && VerticalAlignment == Alignment.Fill) || (!isVertical && Alignment == Alignment.Fill))
  334. {
  335. CursorPosition = idx - start;
  336. }
  337. driver?.SetAttribute (hotColor);
  338. driver?.AddRune (rune);
  339. driver?.SetAttribute (normalColor);
  340. }
  341. else
  342. {
  343. if (isVertical)
  344. {
  345. if (runeWidth == 0)
  346. {
  347. if (lastZeroWidthPos is null)
  348. {
  349. lastZeroWidthPos = new ();
  350. }
  351. int foundIdx = lastZeroWidthPos.IndexOf (
  352. p =>
  353. p is { } && p.Value.Y == current
  354. );
  355. if (foundIdx == -1)
  356. {
  357. current--;
  358. lastZeroWidthPos.Add (new Point (x + 1, current));
  359. }
  360. driver?.Move (x + 1, current);
  361. }
  362. }
  363. driver?.AddRune (rune);
  364. }
  365. if (isVertical)
  366. {
  367. if (runeWidth > 0)
  368. {
  369. current++;
  370. }
  371. }
  372. else
  373. {
  374. current += runeWidth;
  375. }
  376. int nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length
  377. ? runes [idx + 1].GetColumns ()
  378. : 0;
  379. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size)
  380. {
  381. break;
  382. }
  383. }
  384. }
  385. }
  386. /// <summary>
  387. /// Determines if the viewport width will be used or only the text width will be used,
  388. /// If <see langword="true"/> all the viewport area will be filled with whitespaces and the same background color
  389. /// showing a perfect rectangle.
  390. /// </summary>
  391. public bool FillRemaining { get; set; }
  392. /// <summary>Returns the formatted text, constrained to <see cref="ConstrainToSize"/>.</summary>
  393. /// <remarks>
  394. /// If <see cref="NeedsFormat"/> is <see langword="true"/>, causes a format, resetting <see cref="NeedsFormat"/>
  395. /// to <see langword="false"/>.
  396. /// </remarks>
  397. /// <returns>The formatted text.</returns>
  398. public string Format ()
  399. {
  400. var sb = new StringBuilder ();
  401. // Lines_get causes a Format
  402. foreach (string line in GetLines ())
  403. {
  404. sb.AppendLine (line);
  405. }
  406. return sb.ToString ().TrimEnd (Environment.NewLine.ToCharArray ());
  407. }
  408. /// <summary>Gets the size required to hold the formatted text, given the constraints placed by <see cref="ConstrainToSize"/>.</summary>
  409. /// <remarks>Causes a format, resetting <see cref="NeedsFormat"/> to <see langword="false"/>.</remarks>
  410. /// <param name="constrainSize">
  411. /// If provided, will cause the text to be constrained to the provided size instead of <see cref="ConstrainToWidth"/> and
  412. /// <see cref="ConstrainToHeight"/>.
  413. /// </param>
  414. /// <returns>The size required to hold the formatted text.</returns>
  415. public Size FormatAndGetSize (Size? constrainSize = null)
  416. {
  417. if (string.IsNullOrEmpty (Text))
  418. {
  419. return System.Drawing.Size.Empty;
  420. }
  421. int? prevWidth = _constrainToWidth;
  422. int? prevHeight = _constrainToHeight;
  423. if (constrainSize is { })
  424. {
  425. _constrainToWidth = constrainSize?.Width;
  426. _constrainToHeight = constrainSize?.Height;
  427. }
  428. // HACK: Fill normally will fill the entire constraint size, but we need to know the actual size of the text.
  429. Alignment prevAlignment = Alignment;
  430. if (Alignment == Alignment.Fill)
  431. {
  432. Alignment = Alignment.Start;
  433. }
  434. Alignment prevVerticalAlignment = VerticalAlignment;
  435. if (VerticalAlignment == Alignment.Fill)
  436. {
  437. VerticalAlignment = Alignment.Start;
  438. }
  439. // This calls Format
  440. List<string> lines = GetLines ();
  441. // Undo hacks
  442. Alignment = prevAlignment;
  443. VerticalAlignment = prevVerticalAlignment;
  444. if (constrainSize is { })
  445. {
  446. _constrainToWidth = prevWidth ?? null;
  447. _constrainToHeight = prevHeight ?? null;
  448. }
  449. if (lines.Count == 0)
  450. {
  451. return System.Drawing.Size.Empty;
  452. }
  453. int width;
  454. int height;
  455. if (IsVerticalDirection (Direction))
  456. {
  457. width = GetColumnsRequiredForVerticalText (lines, 0, lines.Count, TabWidth);
  458. height = lines.Max (static line => line.Length);
  459. }
  460. else
  461. {
  462. width = lines.Max (static line => line.GetColumns ());
  463. height = lines.Count;
  464. }
  465. return new (width, height);
  466. }
  467. /// <summary>
  468. /// Gets the width or height of the <see cref="TextFormatter.HotKeySpecifier"/> characters
  469. /// in the <see cref="Text"/> property.
  470. /// </summary>
  471. /// <remarks>
  472. /// Only the first HotKey specifier found in <see cref="Text"/> is supported.
  473. /// </remarks>
  474. /// <param name="isWidth">
  475. /// If <see langword="true"/> (the default) the width required for the HotKey specifier is returned. Otherwise, the
  476. /// height is returned.
  477. /// </param>
  478. /// <returns>
  479. /// The number of characters required for the <see cref="TextFormatter.HotKeySpecifier"/>. If the text
  480. /// direction specified
  481. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.
  482. /// </returns>
  483. public int GetHotKeySpecifierLength (bool isWidth = true)
  484. {
  485. if (isWidth)
  486. {
  487. return IsHorizontalDirection (Direction) && Text?.Contains ((char)HotKeySpecifier.Value) == true
  488. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  489. : 0;
  490. }
  491. return IsVerticalDirection (Direction) && Text?.Contains ((char)HotKeySpecifier.Value) == true
  492. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  493. : 0;
  494. }
  495. /// <summary>Gets a list of formatted lines, constrained to <see cref="ConstrainToSize"/>.</summary>
  496. /// <remarks>
  497. /// <para>
  498. /// If the text needs to be formatted (if <see cref="NeedsFormat"/> is <see langword="true"/>)
  499. /// <see cref="Format()"/> will be called and upon return
  500. /// <see cref="NeedsFormat"/> will be <see langword="false"/>.
  501. /// </para>
  502. /// <para>
  503. /// If either of the dimensions of <see cref="ConstrainToSize"/> are zero, the text will not be formatted and no lines will
  504. /// be returned.
  505. /// </para>
  506. /// </remarks>
  507. public List<string> GetLines ()
  508. {
  509. int width = _constrainToWidth.GetValueOrDefault ();
  510. int height = _constrainToHeight.GetValueOrDefault ();
  511. // With this check, we protect against subclasses with overrides of Text
  512. if (string.IsNullOrEmpty (Text) || width == 0 || height == 0)
  513. {
  514. _lines = [string.Empty];
  515. NeedsFormat = false;
  516. return _lines;
  517. }
  518. if (!NeedsFormat)
  519. {
  520. return _lines;
  521. }
  522. string text = _text!;
  523. if (FindHotKey (_text!, HotKeySpecifier, out _hotKeyPos, out Key newHotKey))
  524. {
  525. HotKey = newHotKey;
  526. text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  527. text = ReplaceHotKeyWithTag (text, _hotKeyPos);
  528. }
  529. if (IsVerticalDirection (Direction))
  530. {
  531. int colsWidth = GetSumMaxCharWidth (text, 0, 1, TabWidth);
  532. _lines = Format (
  533. text,
  534. height,
  535. VerticalAlignment == Alignment.Fill,
  536. width > colsWidth && WordWrap,
  537. PreserveTrailingSpaces,
  538. TabWidth,
  539. Direction,
  540. MultiLine,
  541. this
  542. );
  543. colsWidth = GetMaxColsForWidth (_lines, width, TabWidth);
  544. if (_lines.Count > colsWidth)
  545. {
  546. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  547. }
  548. }
  549. else
  550. {
  551. _lines = Format (
  552. text,
  553. width,
  554. Alignment == Alignment.Fill,
  555. height > 1 && WordWrap,
  556. PreserveTrailingSpaces,
  557. TabWidth,
  558. Direction,
  559. MultiLine,
  560. this
  561. );
  562. if (_lines.Count > height)
  563. {
  564. _lines.RemoveRange (height, _lines.Count - height);
  565. }
  566. }
  567. NeedsFormat = false;
  568. return _lines;
  569. }
  570. private int? _constrainToWidth;
  571. /// <summary>Gets or sets the width <see cref="Text"/> will be constrained to when formatted.</summary>
  572. /// <remarks>
  573. /// <para>
  574. /// Does not return the width of the formatted text but the width that will be used to constrain the text when
  575. /// formatted.
  576. /// </para>
  577. /// <para>
  578. /// If <see langword="null"/> the height will be unconstrained. if both <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> are <see langword="null"/> the text will be formatted to the size of the text.
  579. /// </para>
  580. /// <para>
  581. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  582. /// </para>
  583. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  584. /// </remarks>
  585. public int? ConstrainToWidth
  586. {
  587. get => _constrainToWidth;
  588. set
  589. {
  590. if (_constrainToWidth == value)
  591. {
  592. return;
  593. }
  594. ArgumentOutOfRangeException.ThrowIfNegative (value.GetValueOrDefault (), nameof (ConstrainToWidth));
  595. _constrainToWidth = EnableNeedsFormat (value);
  596. }
  597. }
  598. private int? _constrainToHeight;
  599. /// <summary>Gets or sets the height <see cref="Text"/> will be constrained to when formatted.</summary>
  600. /// <remarks>
  601. /// <para>
  602. /// Does not return the height of the formatted text but the height that will be used to constrain the text when
  603. /// formatted.
  604. /// </para>
  605. /// <para>
  606. /// If <see langword="null"/> the height will be unconstrained. if both <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> are <see langword="null"/> the text will be formatted to the size of the text.
  607. /// </para>
  608. /// <para>
  609. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  610. /// </para>
  611. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  612. /// </remarks>
  613. public int? ConstrainToHeight
  614. {
  615. get => _constrainToHeight;
  616. set
  617. {
  618. if (_constrainToHeight == value)
  619. {
  620. return;
  621. }
  622. ArgumentOutOfRangeException.ThrowIfNegative (value.GetValueOrDefault (), nameof (ConstrainToHeight));
  623. _constrainToHeight = EnableNeedsFormat (value);
  624. }
  625. }
  626. /// <summary>Gets or sets the width and height <see cref="Text"/> will be constrained to when formatted.</summary>
  627. /// <remarks>
  628. /// <para>
  629. /// Does not return the size of the formatted text but the size that will be used to constrain the text when
  630. /// formatted.
  631. /// </para>
  632. /// <para>
  633. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  634. /// </para>
  635. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  636. /// </remarks>
  637. public Size? ConstrainToSize
  638. {
  639. get
  640. {
  641. if (_constrainToWidth is null || _constrainToHeight is null)
  642. {
  643. return null;
  644. }
  645. return new Size (_constrainToWidth.Value, _constrainToHeight.Value);
  646. }
  647. set
  648. {
  649. if (value is null)
  650. {
  651. _constrainToWidth = null;
  652. _constrainToHeight = null;
  653. EnableNeedsFormat (true);
  654. }
  655. else
  656. {
  657. _constrainToWidth = EnableNeedsFormat (value.Value.Width);
  658. _constrainToHeight = EnableNeedsFormat (value.Value.Height);
  659. }
  660. }
  661. }
  662. /// <summary>Gets or sets the hot key. Fires the <see cref="HotKeyChanged"/> event.</summary>
  663. public Key HotKey
  664. {
  665. get => _hotKey;
  666. internal set
  667. {
  668. if (_hotKey != value)
  669. {
  670. Key oldKey = _hotKey;
  671. _hotKey = value;
  672. HotKeyChanged?.Invoke (this, new (oldKey, value));
  673. }
  674. }
  675. }
  676. /// <summary>Event invoked when the <see cref="HotKey"/> is changed.</summary>
  677. public event EventHandler<KeyChangedEventArgs>? HotKeyChanged;
  678. /// <summary>The position in the text of the hot key. The hot key will be rendered using the hot color.</summary>
  679. public int HotKeyPos
  680. {
  681. get => _hotKeyPos;
  682. internal set => _hotKeyPos = value;
  683. }
  684. /// <summary>
  685. /// The specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable hot key support for this View
  686. /// instance. The default is '\xffff'.
  687. /// </summary>
  688. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  689. /// <summary>Gets or sets a value indicating whether multi line is allowed.</summary>
  690. /// <remarks>Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.</remarks>
  691. public bool MultiLine
  692. {
  693. get => _multiLine;
  694. set => _multiLine = EnableNeedsFormat (value);
  695. }
  696. /// <summary>Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.</summary>
  697. /// <remarks>
  698. /// <para>If <see langword="false"/> when Draw is called, the Draw call will be faster.</para>
  699. /// <para>Used by <see cref="Draw"/></para>
  700. /// <para>Set to <see langword="true"/> when any of the properties of <see cref="TextFormatter"/> are set.</para>
  701. /// <para>Set to <see langword="false"/> when the text is formatted (if <see cref="GetLines"/> is accessed).</para>
  702. /// </remarks>
  703. public bool NeedsFormat { get; set; }
  704. /// <summary>
  705. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved or not when
  706. /// <see cref="TextFormatter.WordWrap"/> is enabled. If <see langword="true"/> trailing spaces at the end of wrapped
  707. /// lines will be removed when <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  708. /// </summary>
  709. public bool PreserveTrailingSpaces
  710. {
  711. get => _preserveTrailingSpaces;
  712. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  713. }
  714. /// <summary>Gets or sets the number of columns used for a tab.</summary>
  715. public int TabWidth
  716. {
  717. get => _tabWidth;
  718. set => _tabWidth = EnableNeedsFormat (value);
  719. }
  720. /// <summary>The text to be formatted. This string is never modified.</summary>
  721. public string Text
  722. {
  723. get => _text!;
  724. set => _text = EnableNeedsFormat (value);
  725. }
  726. /// <summary>Gets or sets the vertical text-alignment.</summary>
  727. /// <value>The text vertical alignment.</value>
  728. public Alignment VerticalAlignment
  729. {
  730. get => _textVerticalAlignment;
  731. set => _textVerticalAlignment = EnableNeedsFormat (value);
  732. }
  733. /// <summary>Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="ConstrainToSize"/>.</summary>
  734. public bool WordWrap
  735. {
  736. get => _wordWrap;
  737. set => _wordWrap = EnableNeedsFormat (value);
  738. }
  739. /// <summary>Sets <see cref="NeedsFormat"/> to <see langword="true"/> and returns the value.</summary>
  740. /// <typeparam name="T"></typeparam>
  741. /// <param name="value"></param>
  742. /// <returns></returns>
  743. private T EnableNeedsFormat<T> (T value)
  744. {
  745. NeedsFormat = true;
  746. return value;
  747. }
  748. #region Static Members
  749. /// <summary>Check if it is a horizontal direction</summary>
  750. public static bool IsHorizontalDirection (TextDirection textDirection)
  751. {
  752. return textDirection switch
  753. {
  754. TextDirection.LeftRight_TopBottom => true,
  755. TextDirection.LeftRight_BottomTop => true,
  756. TextDirection.RightLeft_TopBottom => true,
  757. TextDirection.RightLeft_BottomTop => true,
  758. _ => false
  759. };
  760. }
  761. /// <summary>Check if it is a vertical direction</summary>
  762. public static bool IsVerticalDirection (TextDirection textDirection)
  763. {
  764. return textDirection switch
  765. {
  766. TextDirection.TopBottom_LeftRight => true,
  767. TextDirection.TopBottom_RightLeft => true,
  768. TextDirection.BottomTop_LeftRight => true,
  769. TextDirection.BottomTop_RightLeft => true,
  770. _ => false
  771. };
  772. }
  773. /// <summary>Check if it is Left to Right direction</summary>
  774. public static bool IsLeftToRight (TextDirection textDirection)
  775. {
  776. return textDirection switch
  777. {
  778. TextDirection.LeftRight_TopBottom => true,
  779. TextDirection.LeftRight_BottomTop => true,
  780. _ => false
  781. };
  782. }
  783. /// <summary>Check if it is Top to Bottom direction</summary>
  784. public static bool IsTopToBottom (TextDirection textDirection)
  785. {
  786. return textDirection switch
  787. {
  788. TextDirection.TopBottom_LeftRight => true,
  789. TextDirection.TopBottom_RightLeft => true,
  790. _ => false
  791. };
  792. }
  793. // TODO: Move to StringExtensions?
  794. private static string StripCRLF (string str, bool keepNewLine = false)
  795. {
  796. List<Rune> runes = str.ToRuneList ();
  797. for (var i = 0; i < runes.Count; i++)
  798. {
  799. switch ((char)runes [i].Value)
  800. {
  801. case '\n':
  802. if (!keepNewLine)
  803. {
  804. runes.RemoveAt (i);
  805. }
  806. break;
  807. case '\r':
  808. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  809. {
  810. runes.RemoveAt (i);
  811. if (!keepNewLine)
  812. {
  813. runes.RemoveAt (i);
  814. }
  815. i++;
  816. }
  817. else
  818. {
  819. if (!keepNewLine)
  820. {
  821. runes.RemoveAt (i);
  822. }
  823. }
  824. break;
  825. }
  826. }
  827. return StringExtensions.ToString (runes);
  828. }
  829. // TODO: Move to StringExtensions?
  830. private static string ReplaceCRLFWithSpace (string str)
  831. {
  832. List<Rune> runes = str.ToRuneList ();
  833. for (var i = 0; i < runes.Count; i++)
  834. {
  835. switch (runes [i].Value)
  836. {
  837. case '\n':
  838. runes [i] = (Rune)' ';
  839. break;
  840. case '\r':
  841. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  842. {
  843. runes [i] = (Rune)' ';
  844. runes.RemoveAt (i + 1);
  845. i++;
  846. }
  847. else
  848. {
  849. runes [i] = (Rune)' ';
  850. }
  851. break;
  852. }
  853. }
  854. return StringExtensions.ToString (runes);
  855. }
  856. // TODO: Move to StringExtensions?
  857. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  858. {
  859. if (tabWidth == 0)
  860. {
  861. return str.Replace ("\t", "");
  862. }
  863. return str.Replace ("\t", new (' ', tabWidth));
  864. }
  865. // TODO: Move to StringExtensions?
  866. /// <summary>
  867. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  868. /// ending newline.
  869. /// </summary>
  870. /// <param name="text">The text.</param>
  871. /// <returns>A list of text without the newline characters.</returns>
  872. public static List<string> SplitNewLine (string text)
  873. {
  874. List<Rune> runes = text.ToRuneList ();
  875. List<string> lines = new ();
  876. var start = 0;
  877. for (var i = 0; i < runes.Count; i++)
  878. {
  879. int end = i;
  880. switch (runes [i].Value)
  881. {
  882. case '\n':
  883. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  884. i++;
  885. start = i;
  886. break;
  887. case '\r':
  888. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  889. {
  890. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  891. i += 2;
  892. start = i;
  893. }
  894. else
  895. {
  896. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  897. i++;
  898. start = i;
  899. }
  900. break;
  901. }
  902. }
  903. switch (runes.Count)
  904. {
  905. case > 0 when lines.Count == 0:
  906. lines.Add (StringExtensions.ToString (runes));
  907. break;
  908. case > 0 when start < runes.Count:
  909. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  910. break;
  911. default:
  912. lines.Add ("");
  913. break;
  914. }
  915. return lines;
  916. }
  917. // TODO: Move to StringExtensions?
  918. /// <summary>
  919. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  920. /// columns. Note that some unicode characters take 2+ columns
  921. /// </summary>
  922. /// <param name="text"></param>
  923. /// <param name="width"></param>
  924. /// <returns></returns>
  925. public static string ClipOrPad (string text, int width)
  926. {
  927. if (string.IsNullOrEmpty (text))
  928. {
  929. return text;
  930. }
  931. // if value is not wide enough
  932. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  933. {
  934. // pad it out with spaces to the given Alignment
  935. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  936. return text + new string (' ', toPad);
  937. }
  938. // value is too wide
  939. return new (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  940. }
  941. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  942. /// <param name="text">The text to word wrap</param>
  943. /// <param name="width">The number of columns to constrain the text to</param>
  944. /// <param name="preserveTrailingSpaces">
  945. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  946. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  947. /// </param>
  948. /// <param name="tabWidth">The number of columns used for a tab.</param>
  949. /// <param name="textDirection">The text direction.</param>
  950. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  951. /// <returns>A list of word wrapped lines.</returns>
  952. /// <remarks>
  953. /// <para>This method does not do any alignment.</para>
  954. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  955. /// <para>
  956. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  957. /// at the end of the last line.
  958. /// </para>
  959. /// </remarks>
  960. /// <returns>A list of lines.</returns>
  961. public static List<string> WordWrapText (
  962. string text,
  963. int width,
  964. bool preserveTrailingSpaces = false,
  965. int tabWidth = 0,
  966. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  967. TextFormatter? textFormatter = null
  968. )
  969. {
  970. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  971. List<string> lines = new ();
  972. if (string.IsNullOrEmpty (text))
  973. {
  974. return lines;
  975. }
  976. List<Rune> runes = StripCRLF (text).ToRuneList ();
  977. int start = Math.Max (
  978. !runes.Contains ((Rune)' ') && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  979. ? runes.Count - width
  980. : 0,
  981. 0);
  982. int end;
  983. if (preserveTrailingSpaces)
  984. {
  985. while ((end = start) < runes.Count)
  986. {
  987. end = GetNextWhiteSpace (start, width, out bool incomplete);
  988. if (end == 0 && incomplete)
  989. {
  990. start = text.GetRuneCount ();
  991. break;
  992. }
  993. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  994. start = end;
  995. if (incomplete)
  996. {
  997. start = text.GetRuneCount ();
  998. break;
  999. }
  1000. }
  1001. }
  1002. else
  1003. {
  1004. if (IsHorizontalDirection (textDirection))
  1005. {
  1006. while ((end = start
  1007. + GetLengthThatFits (
  1008. runes.GetRange (start, runes.Count - start),
  1009. width,
  1010. tabWidth,
  1011. textDirection
  1012. ))
  1013. < runes.Count)
  1014. {
  1015. while (runes [end].Value != ' ' && end > start)
  1016. {
  1017. end--;
  1018. }
  1019. if (end == start)
  1020. {
  1021. end = start
  1022. + GetLengthThatFits (
  1023. runes.GetRange (end, runes.Count - end),
  1024. width,
  1025. tabWidth,
  1026. textDirection
  1027. );
  1028. }
  1029. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  1030. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1031. if (end > start && GetRuneWidth (str, tabWidth, textDirection) <= width + zeroLength)
  1032. {
  1033. lines.Add (str);
  1034. start = end;
  1035. if (runes [end].Value == ' ')
  1036. {
  1037. start++;
  1038. }
  1039. }
  1040. else
  1041. {
  1042. end++;
  1043. start = end;
  1044. }
  1045. }
  1046. }
  1047. else
  1048. {
  1049. while ((end = start + width) < runes.Count)
  1050. {
  1051. while (runes [end].Value != ' ' && end > start)
  1052. {
  1053. end--;
  1054. }
  1055. if (end == start)
  1056. {
  1057. end = start + width;
  1058. }
  1059. var zeroLength = 0;
  1060. for (int i = end; i < runes.Count - start; i++)
  1061. {
  1062. Rune r = runes [i];
  1063. if (r.GetColumns () == 0)
  1064. {
  1065. zeroLength++;
  1066. }
  1067. else
  1068. {
  1069. break;
  1070. }
  1071. }
  1072. lines.Add (
  1073. StringExtensions.ToString (
  1074. runes.GetRange (
  1075. start,
  1076. end - start + zeroLength
  1077. )
  1078. )
  1079. );
  1080. end += zeroLength;
  1081. start = end;
  1082. if (runes [end].Value == ' ')
  1083. {
  1084. start++;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1090. {
  1091. int to = from;
  1092. int length = cLength;
  1093. incomplete = false;
  1094. while (length < cWidth && to < runes.Count)
  1095. {
  1096. Rune rune = runes [to];
  1097. if (IsHorizontalDirection (textDirection))
  1098. {
  1099. length += rune.GetColumns ();
  1100. }
  1101. else
  1102. {
  1103. length++;
  1104. }
  1105. if (length > cWidth)
  1106. {
  1107. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1108. {
  1109. incomplete = true;
  1110. }
  1111. return to;
  1112. }
  1113. switch (rune.Value)
  1114. {
  1115. case ' ' when length == cWidth:
  1116. return to + 1;
  1117. case ' ' when length > cWidth:
  1118. return to;
  1119. case ' ':
  1120. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1121. case '\t':
  1122. {
  1123. length += tabWidth + 1;
  1124. if (length == tabWidth && tabWidth > cWidth)
  1125. {
  1126. return to + 1;
  1127. }
  1128. if (length > cWidth && tabWidth > cWidth)
  1129. {
  1130. return to;
  1131. }
  1132. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1133. }
  1134. default:
  1135. to++;
  1136. break;
  1137. }
  1138. }
  1139. return cLength switch
  1140. {
  1141. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1142. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1143. _ => to
  1144. };
  1145. }
  1146. if (start < text.GetRuneCount ())
  1147. {
  1148. string str = ReplaceTABWithSpaces (
  1149. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1150. tabWidth
  1151. );
  1152. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1153. {
  1154. lines.Add (str);
  1155. }
  1156. }
  1157. return lines;
  1158. }
  1159. /// <summary>Justifies text within a specified width.</summary>
  1160. /// <param name="text">The text to justify.</param>
  1161. /// <param name="width">
  1162. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1163. /// clipped.
  1164. /// </param>
  1165. /// <param name="textAlignment">Alignment.</param>
  1166. /// <param name="textDirection">The text direction.</param>
  1167. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1168. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1169. /// <returns>Justified and clipped text.</returns>
  1170. public static string ClipAndJustify (
  1171. string text,
  1172. int width,
  1173. Alignment textAlignment,
  1174. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1175. int tabWidth = 0,
  1176. TextFormatter? textFormatter = null
  1177. )
  1178. {
  1179. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  1180. }
  1181. /// <summary>Justifies text within a specified width.</summary>
  1182. /// <param name="text">The text to justify.</param>
  1183. /// <param name="width">
  1184. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1185. /// clipped.
  1186. /// </param>
  1187. /// <param name="justify">Justify.</param>
  1188. /// <param name="textDirection">The text direction.</param>
  1189. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1190. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1191. /// <returns>Justified and clipped text.</returns>
  1192. public static string ClipAndJustify (
  1193. string text,
  1194. int width,
  1195. bool justify,
  1196. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1197. int tabWidth = 0,
  1198. TextFormatter? textFormatter = null
  1199. )
  1200. {
  1201. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1202. if (string.IsNullOrEmpty (text))
  1203. {
  1204. return text;
  1205. }
  1206. text = ReplaceTABWithSpaces (text, tabWidth);
  1207. List<Rune> runes = text.ToRuneList ();
  1208. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1209. if (runes.Count - zeroLength > width)
  1210. {
  1211. if (IsHorizontalDirection (textDirection))
  1212. {
  1213. if (textFormatter is { Alignment: Alignment.End })
  1214. {
  1215. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1216. }
  1217. if (textFormatter is { Alignment: Alignment.Center })
  1218. {
  1219. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1220. }
  1221. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1222. }
  1223. if (IsVerticalDirection (textDirection))
  1224. {
  1225. if (textFormatter is { VerticalAlignment: Alignment.End })
  1226. {
  1227. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1228. }
  1229. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1230. {
  1231. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1232. }
  1233. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1234. }
  1235. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1236. }
  1237. if (justify)
  1238. {
  1239. return Justify (text, width, ' ', textDirection, tabWidth);
  1240. }
  1241. if (IsHorizontalDirection (textDirection))
  1242. {
  1243. if (textFormatter is { Alignment: Alignment.End })
  1244. {
  1245. if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1246. {
  1247. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1248. }
  1249. }
  1250. else if (textFormatter is { Alignment: Alignment.Center })
  1251. {
  1252. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1253. }
  1254. else if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1255. {
  1256. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1257. }
  1258. }
  1259. if (IsVerticalDirection (textDirection))
  1260. {
  1261. if (textFormatter is { VerticalAlignment: Alignment.End })
  1262. {
  1263. if (runes.Count - zeroLength > width)
  1264. {
  1265. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1266. }
  1267. }
  1268. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1269. {
  1270. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1271. }
  1272. else if (runes.Count - zeroLength > width)
  1273. {
  1274. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1275. }
  1276. }
  1277. return text;
  1278. }
  1279. private static string GetRangeThatFits (List<Rune> runes, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1280. {
  1281. return StringExtensions.ToString (
  1282. runes.GetRange (
  1283. Math.Max (index, 0),
  1284. GetLengthThatFits (text, width, tabWidth, textDirection)
  1285. )
  1286. );
  1287. }
  1288. /// <summary>
  1289. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1290. /// <c>width</c>. Spaces will not be added to the start or end.
  1291. /// </summary>
  1292. /// <param name="text"></param>
  1293. /// <param name="width"></param>
  1294. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1295. /// <param name="textDirection">The text direction.</param>
  1296. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1297. /// <returns>The justified text.</returns>
  1298. public static string Justify (
  1299. string text,
  1300. int width,
  1301. char spaceChar = ' ',
  1302. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1303. int tabWidth = 0
  1304. )
  1305. {
  1306. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1307. if (string.IsNullOrEmpty (text))
  1308. {
  1309. return text;
  1310. }
  1311. text = ReplaceTABWithSpaces (text, tabWidth);
  1312. string [] words = text.Split (' ');
  1313. int textCount;
  1314. if (IsHorizontalDirection (textDirection))
  1315. {
  1316. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth, textDirection));
  1317. }
  1318. else
  1319. {
  1320. textCount = words.Sum (arg => arg.GetRuneCount ());
  1321. }
  1322. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1323. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1324. var s = new StringBuilder ();
  1325. for (var w = 0; w < words.Length; w++)
  1326. {
  1327. string x = words [w];
  1328. s.Append (x);
  1329. if (w + 1 < words.Length)
  1330. {
  1331. for (var i = 0; i < spaces; i++)
  1332. {
  1333. s.Append (spaceChar);
  1334. }
  1335. }
  1336. if (extras > 0)
  1337. {
  1338. for (var i = 0; i < 1; i++)
  1339. {
  1340. s.Append (spaceChar);
  1341. }
  1342. extras--;
  1343. }
  1344. if (w + 1 == words.Length - 1)
  1345. {
  1346. for (var i = 0; i < extras; i++)
  1347. {
  1348. s.Append (spaceChar);
  1349. }
  1350. }
  1351. }
  1352. return s.ToString ();
  1353. }
  1354. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1355. /// <param name="text"></param>
  1356. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1357. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1358. /// <param name="wordWrap">
  1359. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1360. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1361. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1362. /// </param>
  1363. /// <param name="preserveTrailingSpaces">
  1364. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1365. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1366. /// </param>
  1367. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1368. /// <param name="textDirection">The text direction.</param>
  1369. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1370. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1371. /// <returns>A list of word wrapped lines.</returns>
  1372. /// <remarks>
  1373. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1374. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1375. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1376. /// </remarks>
  1377. public static List<string> Format (
  1378. string text,
  1379. int width,
  1380. Alignment textAlignment,
  1381. bool wordWrap,
  1382. bool preserveTrailingSpaces = false,
  1383. int tabWidth = 0,
  1384. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1385. bool multiLine = false,
  1386. TextFormatter? textFormatter = null
  1387. )
  1388. {
  1389. return Format (
  1390. text,
  1391. width,
  1392. textAlignment == Alignment.Fill,
  1393. wordWrap,
  1394. preserveTrailingSpaces,
  1395. tabWidth,
  1396. textDirection,
  1397. multiLine,
  1398. textFormatter
  1399. );
  1400. }
  1401. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1402. /// <param name="text"></param>
  1403. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1404. /// <param name="justify">Specifies whether the text should be justified.</param>
  1405. /// <param name="wordWrap">
  1406. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1407. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1408. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1409. /// </param>
  1410. /// <param name="preserveTrailingSpaces">
  1411. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1412. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1413. /// </param>
  1414. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1415. /// <param name="textDirection">The text direction.</param>
  1416. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1417. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1418. /// <returns>A list of word wrapped lines.</returns>
  1419. /// <remarks>
  1420. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1421. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1422. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1423. /// </remarks>
  1424. public static List<string> Format (
  1425. string text,
  1426. int width,
  1427. bool justify,
  1428. bool wordWrap,
  1429. bool preserveTrailingSpaces = false,
  1430. int tabWidth = 0,
  1431. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1432. bool multiLine = false,
  1433. TextFormatter? textFormatter = null
  1434. )
  1435. {
  1436. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1437. List<string> lineResult = new ();
  1438. if (string.IsNullOrEmpty (text) || width == 0)
  1439. {
  1440. lineResult.Add (string.Empty);
  1441. return lineResult;
  1442. }
  1443. if (!wordWrap)
  1444. {
  1445. text = ReplaceTABWithSpaces (text, tabWidth);
  1446. if (multiLine)
  1447. {
  1448. // Abhorrent case: Just a new line
  1449. if (text == "\n")
  1450. {
  1451. lineResult.Add (string.Empty);
  1452. return lineResult;
  1453. }
  1454. string []? lines = null;
  1455. if (text.Contains ("\r\n"))
  1456. {
  1457. lines = text.Split ("\r\n");
  1458. }
  1459. else if (text.Contains ('\n'))
  1460. {
  1461. lines = text.Split ('\n');
  1462. }
  1463. lines ??= new [] { text };
  1464. foreach (string line in lines)
  1465. {
  1466. lineResult.Add (
  1467. ClipAndJustify (
  1468. PerformCorrectFormatDirection (textDirection, line),
  1469. width,
  1470. justify,
  1471. textDirection,
  1472. tabWidth,
  1473. textFormatter));
  1474. }
  1475. return PerformCorrectFormatDirection (textDirection, lineResult);
  1476. }
  1477. text = ReplaceCRLFWithSpace (text);
  1478. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1479. return PerformCorrectFormatDirection (textDirection, lineResult);
  1480. }
  1481. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1482. int runeCount = runes.Count;
  1483. var lp = 0;
  1484. for (var i = 0; i < runeCount; i++)
  1485. {
  1486. Rune c = runes [i];
  1487. if (c.Value == '\n')
  1488. {
  1489. List<string> wrappedLines =
  1490. WordWrapText (
  1491. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1492. width,
  1493. preserveTrailingSpaces,
  1494. tabWidth,
  1495. textDirection,
  1496. textFormatter
  1497. );
  1498. foreach (string line in wrappedLines)
  1499. {
  1500. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1501. }
  1502. if (wrappedLines.Count == 0)
  1503. {
  1504. lineResult.Add (string.Empty);
  1505. }
  1506. lp = i + 1;
  1507. }
  1508. }
  1509. foreach (string line in WordWrapText (
  1510. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1511. width,
  1512. preserveTrailingSpaces,
  1513. tabWidth,
  1514. textDirection,
  1515. textFormatter
  1516. ))
  1517. {
  1518. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1519. }
  1520. return PerformCorrectFormatDirection (textDirection, lineResult);
  1521. }
  1522. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1523. {
  1524. return textDirection switch
  1525. {
  1526. TextDirection.RightLeft_BottomTop
  1527. or TextDirection.RightLeft_TopBottom
  1528. or TextDirection.BottomTop_LeftRight
  1529. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1530. _ => line
  1531. };
  1532. }
  1533. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1534. {
  1535. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1536. }
  1537. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1538. {
  1539. return textDirection switch
  1540. {
  1541. TextDirection.TopBottom_RightLeft
  1542. or TextDirection.LeftRight_BottomTop
  1543. or TextDirection.RightLeft_BottomTop
  1544. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1545. _ => lines
  1546. };
  1547. }
  1548. /// <summary>
  1549. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1550. /// </summary>
  1551. /// <remarks>
  1552. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1553. /// glyphs (e.g. Arabic).
  1554. /// </remarks>
  1555. /// <param name="lines">The lines.</param>
  1556. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1557. /// <param name="linesCount">
  1558. /// The number of lines to process (if less than <c>lines.Count</c>, any lines after will be
  1559. /// ignored).
  1560. /// </param>
  1561. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1562. /// <returns>The width required.</returns>
  1563. public static int GetColumnsRequiredForVerticalText (
  1564. List<string> lines,
  1565. int startLine = -1,
  1566. int linesCount = -1,
  1567. int tabWidth = 0
  1568. )
  1569. {
  1570. var max = 0;
  1571. for (int i = startLine == -1 ? 0 : startLine;
  1572. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1573. i++)
  1574. {
  1575. string runes = lines [i];
  1576. if (runes.Length > 0)
  1577. {
  1578. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1579. }
  1580. }
  1581. return max;
  1582. }
  1583. /// <summary>
  1584. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1585. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1586. /// </summary>
  1587. /// <remarks>
  1588. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1589. /// glyphs (e.g. Arabic).
  1590. /// </remarks>
  1591. /// <param name="text">Text, may contain newlines.</param>
  1592. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1593. /// <returns>The length of the longest line.</returns>
  1594. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1595. {
  1596. List<string> result = SplitNewLine (text);
  1597. return result.Max (x => GetRuneWidth (x, tabWidth));
  1598. }
  1599. /// <summary>
  1600. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1601. /// <paramref name="length"/>.
  1602. /// </summary>
  1603. /// <remarks>
  1604. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1605. /// glyphs (e.g. Arabic).
  1606. /// </remarks>
  1607. /// <param name="text">The text.</param>
  1608. /// <param name="startIndex">The start index.</param>
  1609. /// <param name="length">The length.</param>
  1610. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1611. /// <returns>The maximum characters width.</returns>
  1612. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1613. {
  1614. var max = 0;
  1615. Rune [] runes = text.ToRunes ();
  1616. for (int i = startIndex == -1 ? 0 : startIndex;
  1617. i < (length == -1 ? runes.Length : startIndex + length);
  1618. i++)
  1619. {
  1620. max += GetRuneWidth (runes [i], tabWidth);
  1621. }
  1622. return max;
  1623. }
  1624. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</summary>
  1625. /// <remarks>
  1626. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1627. /// glyphs (e.g. Arabic).
  1628. /// </remarks>
  1629. /// <param name="text">The text.</param>
  1630. /// <param name="width">The width.</param>
  1631. /// <param name="tabWidth">The width used for a tab.</param>
  1632. /// <param name="textDirection">The text direction.</param>
  1633. /// <returns>The index of the text that fit the width.</returns>
  1634. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1635. {
  1636. return GetLengthThatFits (text?.ToRuneList () ?? [], width, tabWidth, textDirection);
  1637. }
  1638. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="width"/>.</summary>
  1639. /// <remarks>
  1640. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1641. /// glyphs (e.g. Arabic).
  1642. /// </remarks>
  1643. /// <param name="runes">The list of runes.</param>
  1644. /// <param name="width">The width.</param>
  1645. /// <param name="tabWidth">The width used for a tab.</param>
  1646. /// <param name="textDirection">The text direction.</param>
  1647. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="width"/>.</returns>
  1648. public static int GetLengthThatFits (List<Rune> runes, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1649. {
  1650. if (runes is null || runes.Count == 0)
  1651. {
  1652. return 0;
  1653. }
  1654. var runesLength = 0;
  1655. var runeIdx = 0;
  1656. for (; runeIdx < runes.Count; runeIdx++)
  1657. {
  1658. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth, textDirection);
  1659. if (runesLength + runeWidth > width)
  1660. {
  1661. break;
  1662. }
  1663. runesLength += runeWidth;
  1664. }
  1665. return runeIdx;
  1666. }
  1667. private static int GetRuneWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1668. {
  1669. return GetRuneWidth (str.EnumerateRunes ().ToList (), tabWidth, textDirection);
  1670. }
  1671. private static int GetRuneWidth (List<Rune> runes, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1672. {
  1673. return runes.Sum (r => GetRuneWidth (r, tabWidth, textDirection));
  1674. }
  1675. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1676. {
  1677. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : 1;
  1678. if (rune.Value == '\t')
  1679. {
  1680. return tabWidth;
  1681. }
  1682. if (runeWidth < 0 || runeWidth > 0)
  1683. {
  1684. return Math.Max (runeWidth, 1);
  1685. }
  1686. return runeWidth;
  1687. }
  1688. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  1689. /// <remarks>
  1690. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1691. /// glyphs (e.g. Arabic).
  1692. /// </remarks>
  1693. /// <param name="lines">The lines.</param>
  1694. /// <param name="width">The width.</param>
  1695. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1696. /// <returns>The index of the list that fit the width.</returns>
  1697. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  1698. {
  1699. var runesLength = 0;
  1700. var lineIdx = 0;
  1701. for (; lineIdx < lines.Count; lineIdx++)
  1702. {
  1703. List<Rune> runes = lines [lineIdx].ToRuneList ();
  1704. int maxRruneWidth = runes.Count > 0
  1705. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  1706. : 1;
  1707. if (runesLength + maxRruneWidth > width)
  1708. {
  1709. break;
  1710. }
  1711. runesLength += maxRruneWidth;
  1712. }
  1713. return lineIdx;
  1714. }
  1715. /// <summary>Calculates the rectangle required to hold text, assuming no word wrapping or alignment.</summary>
  1716. /// <remarks>
  1717. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1718. /// glyphs (e.g. Arabic).
  1719. /// </remarks>
  1720. /// <param name="x">The x location of the rectangle</param>
  1721. /// <param name="y">The y location of the rectangle</param>
  1722. /// <param name="text">The text to measure</param>
  1723. /// <param name="direction">The text direction.</param>
  1724. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1725. /// <returns></returns>
  1726. [Obsolete ("CalcRect is deprecated, FormatAndGetSize instead.")]
  1727. internal static Rectangle CalcRect (
  1728. int x,
  1729. int y,
  1730. string text,
  1731. TextDirection direction = TextDirection.LeftRight_TopBottom,
  1732. int tabWidth = 0
  1733. )
  1734. {
  1735. if (string.IsNullOrEmpty (text))
  1736. {
  1737. return new (new (x, y), System.Drawing.Size.Empty);
  1738. }
  1739. int w, h;
  1740. if (IsHorizontalDirection (direction))
  1741. {
  1742. var mw = 0;
  1743. var ml = 1;
  1744. var cols = 0;
  1745. foreach (Rune rune in text.EnumerateRunes ())
  1746. {
  1747. if (rune.Value == '\n')
  1748. {
  1749. ml++;
  1750. if (cols > mw)
  1751. {
  1752. mw = cols;
  1753. }
  1754. cols = 0;
  1755. }
  1756. else if (rune.Value != '\r')
  1757. {
  1758. cols++;
  1759. var rw = 0;
  1760. if (rune.Value == '\t')
  1761. {
  1762. rw += tabWidth - 1;
  1763. }
  1764. else
  1765. {
  1766. rw = rune.GetColumns ();
  1767. if (rw > 0)
  1768. {
  1769. rw--;
  1770. }
  1771. else if (rw == 0)
  1772. {
  1773. cols--;
  1774. }
  1775. }
  1776. cols += rw;
  1777. }
  1778. }
  1779. if (cols > mw)
  1780. {
  1781. mw = cols;
  1782. }
  1783. w = mw;
  1784. h = ml;
  1785. }
  1786. else
  1787. {
  1788. int vw = 1, cw = 1;
  1789. var vh = 0;
  1790. var rows = 0;
  1791. foreach (Rune rune in text.EnumerateRunes ())
  1792. {
  1793. if (rune.Value == '\n')
  1794. {
  1795. vw++;
  1796. if (rows > vh)
  1797. {
  1798. vh = rows;
  1799. }
  1800. rows = 0;
  1801. cw = 1;
  1802. }
  1803. else if (rune.Value != '\r')
  1804. {
  1805. rows++;
  1806. var rw = 0;
  1807. if (rune.Value == '\t')
  1808. {
  1809. rw += tabWidth - 1;
  1810. rows += rw;
  1811. }
  1812. else
  1813. {
  1814. rw = rune.GetColumns ();
  1815. if (rw == 0)
  1816. {
  1817. rows--;
  1818. }
  1819. else if (cw < rw)
  1820. {
  1821. cw = rw;
  1822. vw++;
  1823. }
  1824. }
  1825. }
  1826. }
  1827. if (rows > vh)
  1828. {
  1829. vh = rows;
  1830. }
  1831. w = vw;
  1832. h = vh;
  1833. }
  1834. return new (x, y, w, h);
  1835. }
  1836. /// <summary>Finds the HotKey and its location in text.</summary>
  1837. /// <param name="text">The text to look in.</param>
  1838. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  1839. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  1840. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  1841. /// <param name="firstUpperCase">
  1842. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  1843. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  1844. /// Defaults to <see langword="false"/>.
  1845. /// </param>
  1846. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  1847. public static bool FindHotKey (
  1848. string text,
  1849. Rune hotKeySpecifier,
  1850. out int hotPos,
  1851. out Key hotKey,
  1852. bool firstUpperCase = false
  1853. )
  1854. {
  1855. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  1856. {
  1857. hotPos = -1;
  1858. hotKey = Key.Empty;
  1859. return false;
  1860. }
  1861. var curHotKey = (Rune)0;
  1862. int curHotPos = -1;
  1863. // Use first hot_key char passed into 'hotKey'.
  1864. // TODO: Ignore hot_key of two are provided
  1865. // TODO: Do not support non-alphanumeric chars that can't be typed
  1866. var i = 0;
  1867. foreach (Rune c in text.EnumerateRunes ())
  1868. {
  1869. if ((char)c.Value != 0xFFFD)
  1870. {
  1871. if (c == hotKeySpecifier)
  1872. {
  1873. curHotPos = i;
  1874. }
  1875. else if (curHotPos > -1)
  1876. {
  1877. curHotKey = c;
  1878. break;
  1879. }
  1880. }
  1881. i++;
  1882. }
  1883. // Legacy support - use first upper case char if the specifier was not found
  1884. if (curHotPos == -1 && firstUpperCase)
  1885. {
  1886. i = 0;
  1887. foreach (Rune c in text.EnumerateRunes ())
  1888. {
  1889. if ((char)c.Value != 0xFFFD)
  1890. {
  1891. if (Rune.IsUpper (c))
  1892. {
  1893. curHotKey = c;
  1894. curHotPos = i;
  1895. break;
  1896. }
  1897. }
  1898. i++;
  1899. }
  1900. }
  1901. if (curHotKey != (Rune)0 && curHotPos != -1)
  1902. {
  1903. hotPos = curHotPos;
  1904. var newHotKey = (KeyCode)curHotKey.Value;
  1905. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  1906. {
  1907. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  1908. {
  1909. newHotKey &= ~KeyCode.Space;
  1910. }
  1911. hotKey = newHotKey;
  1912. //hotKey.Scope = KeyBindingScope.HotKey;
  1913. return true;
  1914. }
  1915. }
  1916. hotPos = -1;
  1917. hotKey = KeyCode.Null;
  1918. return false;
  1919. }
  1920. /// <summary>
  1921. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  1922. /// hotkey.
  1923. /// </summary>
  1924. /// <param name="text">The text to tag the hotkey in.</param>
  1925. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1926. /// <returns>The text with the hotkey tagged.</returns>
  1927. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  1928. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  1929. {
  1930. // Set the high bit
  1931. List<Rune> runes = text.ToRuneList ();
  1932. if (Rune.IsLetterOrDigit (runes [hotPos]))
  1933. {
  1934. runes [hotPos] = new ((uint)runes [hotPos].Value);
  1935. }
  1936. return StringExtensions.ToString (runes);
  1937. }
  1938. /// <summary>Removes the hotkey specifier from text.</summary>
  1939. /// <param name="text">The text to manipulate.</param>
  1940. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1941. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1942. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1943. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  1944. {
  1945. if (string.IsNullOrEmpty (text))
  1946. {
  1947. return text;
  1948. }
  1949. // Scan
  1950. var start = string.Empty;
  1951. var i = 0;
  1952. foreach (Rune c in text)
  1953. {
  1954. if (c == hotKeySpecifier && i == hotPos)
  1955. {
  1956. i++;
  1957. continue;
  1958. }
  1959. start += c;
  1960. i++;
  1961. }
  1962. return start;
  1963. }
  1964. #endregion // Static Members
  1965. }