TextFormatter.cs 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283
  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. /// If <see langword="null"/> both the width and height will be unconstrained and text will be formatted to the size of the text.
  634. /// </para>
  635. /// <para>
  636. /// Setting this property is the same as setting <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> separately.
  637. /// </para>
  638. /// <para>
  639. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  640. /// </para>
  641. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  642. /// </remarks>
  643. public Size? ConstrainToSize
  644. {
  645. get
  646. {
  647. if (_constrainToWidth is null || _constrainToHeight is null)
  648. {
  649. return null;
  650. }
  651. return new Size (_constrainToWidth.Value, _constrainToHeight.Value);
  652. }
  653. set
  654. {
  655. if (value is null)
  656. {
  657. _constrainToWidth = null;
  658. _constrainToHeight = null;
  659. EnableNeedsFormat (true);
  660. }
  661. else
  662. {
  663. _constrainToWidth = EnableNeedsFormat (value.Value.Width);
  664. _constrainToHeight = EnableNeedsFormat (value.Value.Height);
  665. }
  666. }
  667. }
  668. /// <summary>Gets or sets the hot key. Fires the <see cref="HotKeyChanged"/> event.</summary>
  669. public Key HotKey
  670. {
  671. get => _hotKey;
  672. internal set
  673. {
  674. if (_hotKey != value)
  675. {
  676. Key oldKey = _hotKey;
  677. _hotKey = value;
  678. HotKeyChanged?.Invoke (this, new (oldKey, value));
  679. }
  680. }
  681. }
  682. /// <summary>Event invoked when the <see cref="HotKey"/> is changed.</summary>
  683. public event EventHandler<KeyChangedEventArgs>? HotKeyChanged;
  684. /// <summary>The position in the text of the hot key. The hot key will be rendered using the hot color.</summary>
  685. public int HotKeyPos
  686. {
  687. get => _hotKeyPos;
  688. internal set => _hotKeyPos = value;
  689. }
  690. /// <summary>
  691. /// The specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable hot key support for this View
  692. /// instance. The default is '\xffff'.
  693. /// </summary>
  694. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  695. /// <summary>Gets or sets a value indicating whether multi line is allowed.</summary>
  696. /// <remarks>Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.</remarks>
  697. public bool MultiLine
  698. {
  699. get => _multiLine;
  700. set => _multiLine = EnableNeedsFormat (value);
  701. }
  702. /// <summary>Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.</summary>
  703. /// <remarks>
  704. /// <para>If <see langword="false"/> when Draw is called, the Draw call will be faster.</para>
  705. /// <para>Used by <see cref="Draw"/></para>
  706. /// <para>Set to <see langword="true"/> when any of the properties of <see cref="TextFormatter"/> are set.</para>
  707. /// <para>Set to <see langword="false"/> when the text is formatted (if <see cref="GetLines"/> is accessed).</para>
  708. /// </remarks>
  709. public bool NeedsFormat { get; set; }
  710. /// <summary>
  711. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved or not when
  712. /// <see cref="TextFormatter.WordWrap"/> is enabled. If <see langword="true"/> trailing spaces at the end of wrapped
  713. /// lines will be removed when <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  714. /// </summary>
  715. public bool PreserveTrailingSpaces
  716. {
  717. get => _preserveTrailingSpaces;
  718. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  719. }
  720. /// <summary>Gets or sets the number of columns used for a tab.</summary>
  721. public int TabWidth
  722. {
  723. get => _tabWidth;
  724. set => _tabWidth = EnableNeedsFormat (value);
  725. }
  726. /// <summary>The text to be formatted. This string is never modified.</summary>
  727. public string Text
  728. {
  729. get => _text!;
  730. set => _text = EnableNeedsFormat (value);
  731. }
  732. /// <summary>Gets or sets the vertical text-alignment.</summary>
  733. /// <value>The text vertical alignment.</value>
  734. public Alignment VerticalAlignment
  735. {
  736. get => _textVerticalAlignment;
  737. set => _textVerticalAlignment = EnableNeedsFormat (value);
  738. }
  739. /// <summary>Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="ConstrainToSize"/>.</summary>
  740. public bool WordWrap
  741. {
  742. get => _wordWrap;
  743. set => _wordWrap = EnableNeedsFormat (value);
  744. }
  745. /// <summary>Sets <see cref="NeedsFormat"/> to <see langword="true"/> and returns the value.</summary>
  746. /// <typeparam name="T"></typeparam>
  747. /// <param name="value"></param>
  748. /// <returns></returns>
  749. private T EnableNeedsFormat<T> (T value)
  750. {
  751. NeedsFormat = true;
  752. return value;
  753. }
  754. #region Static Members
  755. /// <summary>Check if it is a horizontal direction</summary>
  756. public static bool IsHorizontalDirection (TextDirection textDirection)
  757. {
  758. return textDirection switch
  759. {
  760. TextDirection.LeftRight_TopBottom => true,
  761. TextDirection.LeftRight_BottomTop => true,
  762. TextDirection.RightLeft_TopBottom => true,
  763. TextDirection.RightLeft_BottomTop => true,
  764. _ => false
  765. };
  766. }
  767. /// <summary>Check if it is a vertical direction</summary>
  768. public static bool IsVerticalDirection (TextDirection textDirection)
  769. {
  770. return textDirection switch
  771. {
  772. TextDirection.TopBottom_LeftRight => true,
  773. TextDirection.TopBottom_RightLeft => true,
  774. TextDirection.BottomTop_LeftRight => true,
  775. TextDirection.BottomTop_RightLeft => true,
  776. _ => false
  777. };
  778. }
  779. /// <summary>Check if it is Left to Right direction</summary>
  780. public static bool IsLeftToRight (TextDirection textDirection)
  781. {
  782. return textDirection switch
  783. {
  784. TextDirection.LeftRight_TopBottom => true,
  785. TextDirection.LeftRight_BottomTop => true,
  786. _ => false
  787. };
  788. }
  789. /// <summary>Check if it is Top to Bottom direction</summary>
  790. public static bool IsTopToBottom (TextDirection textDirection)
  791. {
  792. return textDirection switch
  793. {
  794. TextDirection.TopBottom_LeftRight => true,
  795. TextDirection.TopBottom_RightLeft => true,
  796. _ => false
  797. };
  798. }
  799. // TODO: Move to StringExtensions?
  800. private static string StripCRLF (string str, bool keepNewLine = false)
  801. {
  802. List<Rune> runes = str.ToRuneList ();
  803. for (var i = 0; i < runes.Count; i++)
  804. {
  805. switch ((char)runes [i].Value)
  806. {
  807. case '\n':
  808. if (!keepNewLine)
  809. {
  810. runes.RemoveAt (i);
  811. }
  812. break;
  813. case '\r':
  814. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  815. {
  816. runes.RemoveAt (i);
  817. if (!keepNewLine)
  818. {
  819. runes.RemoveAt (i);
  820. }
  821. i++;
  822. }
  823. else
  824. {
  825. if (!keepNewLine)
  826. {
  827. runes.RemoveAt (i);
  828. }
  829. }
  830. break;
  831. }
  832. }
  833. return StringExtensions.ToString (runes);
  834. }
  835. // TODO: Move to StringExtensions?
  836. private static string ReplaceCRLFWithSpace (string str)
  837. {
  838. List<Rune> runes = str.ToRuneList ();
  839. for (var i = 0; i < runes.Count; i++)
  840. {
  841. switch (runes [i].Value)
  842. {
  843. case '\n':
  844. runes [i] = (Rune)' ';
  845. break;
  846. case '\r':
  847. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  848. {
  849. runes [i] = (Rune)' ';
  850. runes.RemoveAt (i + 1);
  851. i++;
  852. }
  853. else
  854. {
  855. runes [i] = (Rune)' ';
  856. }
  857. break;
  858. }
  859. }
  860. return StringExtensions.ToString (runes);
  861. }
  862. // TODO: Move to StringExtensions?
  863. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  864. {
  865. if (tabWidth == 0)
  866. {
  867. return str.Replace ("\t", "");
  868. }
  869. return str.Replace ("\t", new (' ', tabWidth));
  870. }
  871. // TODO: Move to StringExtensions?
  872. /// <summary>
  873. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  874. /// ending newline.
  875. /// </summary>
  876. /// <param name="text">The text.</param>
  877. /// <returns>A list of text without the newline characters.</returns>
  878. public static List<string> SplitNewLine (string text)
  879. {
  880. List<Rune> runes = text.ToRuneList ();
  881. List<string> lines = new ();
  882. var start = 0;
  883. for (var i = 0; i < runes.Count; i++)
  884. {
  885. int end = i;
  886. switch (runes [i].Value)
  887. {
  888. case '\n':
  889. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  890. i++;
  891. start = i;
  892. break;
  893. case '\r':
  894. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  895. {
  896. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  897. i += 2;
  898. start = i;
  899. }
  900. else
  901. {
  902. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  903. i++;
  904. start = i;
  905. }
  906. break;
  907. }
  908. }
  909. switch (runes.Count)
  910. {
  911. case > 0 when lines.Count == 0:
  912. lines.Add (StringExtensions.ToString (runes));
  913. break;
  914. case > 0 when start < runes.Count:
  915. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  916. break;
  917. default:
  918. lines.Add ("");
  919. break;
  920. }
  921. return lines;
  922. }
  923. // TODO: Move to StringExtensions?
  924. /// <summary>
  925. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  926. /// columns. Note that some unicode characters take 2+ columns
  927. /// </summary>
  928. /// <param name="text"></param>
  929. /// <param name="width"></param>
  930. /// <returns></returns>
  931. public static string ClipOrPad (string text, int width)
  932. {
  933. if (string.IsNullOrEmpty (text))
  934. {
  935. return text;
  936. }
  937. // if value is not wide enough
  938. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  939. {
  940. // pad it out with spaces to the given Alignment
  941. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  942. return text + new string (' ', toPad);
  943. }
  944. // value is too wide
  945. return new (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  946. }
  947. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  948. /// <param name="text">The text to word wrap</param>
  949. /// <param name="width">The number of columns to constrain the text to</param>
  950. /// <param name="preserveTrailingSpaces">
  951. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  952. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  953. /// </param>
  954. /// <param name="tabWidth">The number of columns used for a tab.</param>
  955. /// <param name="textDirection">The text direction.</param>
  956. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  957. /// <returns>A list of word wrapped lines.</returns>
  958. /// <remarks>
  959. /// <para>This method does not do any alignment.</para>
  960. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  961. /// <para>
  962. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  963. /// at the end of the last line.
  964. /// </para>
  965. /// </remarks>
  966. /// <returns>A list of lines.</returns>
  967. public static List<string> WordWrapText (
  968. string text,
  969. int width,
  970. bool preserveTrailingSpaces = false,
  971. int tabWidth = 0,
  972. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  973. TextFormatter? textFormatter = null
  974. )
  975. {
  976. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  977. List<string> lines = new ();
  978. if (string.IsNullOrEmpty (text))
  979. {
  980. return lines;
  981. }
  982. List<Rune> runes = StripCRLF (text).ToRuneList ();
  983. int start = Math.Max (
  984. !runes.Contains ((Rune)' ') && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  985. ? runes.Count - width
  986. : 0,
  987. 0);
  988. int end;
  989. if (preserveTrailingSpaces)
  990. {
  991. while ((end = start) < runes.Count)
  992. {
  993. end = GetNextWhiteSpace (start, width, out bool incomplete);
  994. if (end == 0 && incomplete)
  995. {
  996. start = text.GetRuneCount ();
  997. break;
  998. }
  999. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1000. start = end;
  1001. if (incomplete)
  1002. {
  1003. start = text.GetRuneCount ();
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. else
  1009. {
  1010. if (IsHorizontalDirection (textDirection))
  1011. {
  1012. while ((end = start
  1013. + GetLengthThatFits (
  1014. runes.GetRange (start, runes.Count - start),
  1015. width,
  1016. tabWidth,
  1017. textDirection
  1018. ))
  1019. < runes.Count)
  1020. {
  1021. while (runes [end].Value != ' ' && end > start)
  1022. {
  1023. end--;
  1024. }
  1025. if (end == start)
  1026. {
  1027. end = start
  1028. + GetLengthThatFits (
  1029. runes.GetRange (end, runes.Count - end),
  1030. width,
  1031. tabWidth,
  1032. textDirection
  1033. );
  1034. }
  1035. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  1036. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1037. if (end > start && GetRuneWidth (str, tabWidth, textDirection) <= width + zeroLength)
  1038. {
  1039. lines.Add (str);
  1040. start = end;
  1041. if (runes [end].Value == ' ')
  1042. {
  1043. start++;
  1044. }
  1045. }
  1046. else
  1047. {
  1048. end++;
  1049. start = end;
  1050. }
  1051. }
  1052. }
  1053. else
  1054. {
  1055. while ((end = start + width) < runes.Count)
  1056. {
  1057. while (runes [end].Value != ' ' && end > start)
  1058. {
  1059. end--;
  1060. }
  1061. if (end == start)
  1062. {
  1063. end = start + width;
  1064. }
  1065. var zeroLength = 0;
  1066. for (int i = end; i < runes.Count - start; i++)
  1067. {
  1068. Rune r = runes [i];
  1069. if (r.GetColumns () == 0)
  1070. {
  1071. zeroLength++;
  1072. }
  1073. else
  1074. {
  1075. break;
  1076. }
  1077. }
  1078. lines.Add (
  1079. StringExtensions.ToString (
  1080. runes.GetRange (
  1081. start,
  1082. end - start + zeroLength
  1083. )
  1084. )
  1085. );
  1086. end += zeroLength;
  1087. start = end;
  1088. if (runes [end].Value == ' ')
  1089. {
  1090. start++;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1096. {
  1097. int to = from;
  1098. int length = cLength;
  1099. incomplete = false;
  1100. while (length < cWidth && to < runes.Count)
  1101. {
  1102. Rune rune = runes [to];
  1103. if (IsHorizontalDirection (textDirection))
  1104. {
  1105. length += rune.GetColumns ();
  1106. }
  1107. else
  1108. {
  1109. length++;
  1110. }
  1111. if (length > cWidth)
  1112. {
  1113. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1114. {
  1115. incomplete = true;
  1116. }
  1117. return to;
  1118. }
  1119. switch (rune.Value)
  1120. {
  1121. case ' ' when length == cWidth:
  1122. return to + 1;
  1123. case ' ' when length > cWidth:
  1124. return to;
  1125. case ' ':
  1126. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1127. case '\t':
  1128. {
  1129. length += tabWidth + 1;
  1130. if (length == tabWidth && tabWidth > cWidth)
  1131. {
  1132. return to + 1;
  1133. }
  1134. if (length > cWidth && tabWidth > cWidth)
  1135. {
  1136. return to;
  1137. }
  1138. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1139. }
  1140. default:
  1141. to++;
  1142. break;
  1143. }
  1144. }
  1145. return cLength switch
  1146. {
  1147. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1148. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1149. _ => to
  1150. };
  1151. }
  1152. if (start < text.GetRuneCount ())
  1153. {
  1154. string str = ReplaceTABWithSpaces (
  1155. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1156. tabWidth
  1157. );
  1158. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1159. {
  1160. lines.Add (str);
  1161. }
  1162. }
  1163. return lines;
  1164. }
  1165. /// <summary>Justifies text within a specified width.</summary>
  1166. /// <param name="text">The text to justify.</param>
  1167. /// <param name="width">
  1168. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1169. /// clipped.
  1170. /// </param>
  1171. /// <param name="textAlignment">Alignment.</param>
  1172. /// <param name="textDirection">The text direction.</param>
  1173. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1174. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1175. /// <returns>Justified and clipped text.</returns>
  1176. public static string ClipAndJustify (
  1177. string text,
  1178. int width,
  1179. Alignment textAlignment,
  1180. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1181. int tabWidth = 0,
  1182. TextFormatter? textFormatter = null
  1183. )
  1184. {
  1185. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  1186. }
  1187. /// <summary>Justifies text within a specified width.</summary>
  1188. /// <param name="text">The text to justify.</param>
  1189. /// <param name="width">
  1190. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1191. /// clipped.
  1192. /// </param>
  1193. /// <param name="justify">Justify.</param>
  1194. /// <param name="textDirection">The text direction.</param>
  1195. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1196. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1197. /// <returns>Justified and clipped text.</returns>
  1198. public static string ClipAndJustify (
  1199. string text,
  1200. int width,
  1201. bool justify,
  1202. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1203. int tabWidth = 0,
  1204. TextFormatter? textFormatter = null
  1205. )
  1206. {
  1207. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1208. if (string.IsNullOrEmpty (text))
  1209. {
  1210. return text;
  1211. }
  1212. text = ReplaceTABWithSpaces (text, tabWidth);
  1213. List<Rune> runes = text.ToRuneList ();
  1214. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1215. if (runes.Count - zeroLength > width)
  1216. {
  1217. if (IsHorizontalDirection (textDirection))
  1218. {
  1219. if (textFormatter is { Alignment: Alignment.End })
  1220. {
  1221. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1222. }
  1223. if (textFormatter is { Alignment: Alignment.Center })
  1224. {
  1225. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1226. }
  1227. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1228. }
  1229. if (IsVerticalDirection (textDirection))
  1230. {
  1231. if (textFormatter is { VerticalAlignment: Alignment.End })
  1232. {
  1233. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1234. }
  1235. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1236. {
  1237. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1238. }
  1239. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1240. }
  1241. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1242. }
  1243. if (justify)
  1244. {
  1245. return Justify (text, width, ' ', textDirection, tabWidth);
  1246. }
  1247. if (IsHorizontalDirection (textDirection))
  1248. {
  1249. if (textFormatter is { Alignment: Alignment.End })
  1250. {
  1251. if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1252. {
  1253. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1254. }
  1255. }
  1256. else if (textFormatter is { Alignment: Alignment.Center })
  1257. {
  1258. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1259. }
  1260. else if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1261. {
  1262. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1263. }
  1264. }
  1265. if (IsVerticalDirection (textDirection))
  1266. {
  1267. if (textFormatter is { VerticalAlignment: Alignment.End })
  1268. {
  1269. if (runes.Count - zeroLength > width)
  1270. {
  1271. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1272. }
  1273. }
  1274. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1275. {
  1276. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1277. }
  1278. else if (runes.Count - zeroLength > width)
  1279. {
  1280. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1281. }
  1282. }
  1283. return text;
  1284. }
  1285. private static string GetRangeThatFits (List<Rune> runes, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1286. {
  1287. return StringExtensions.ToString (
  1288. runes.GetRange (
  1289. Math.Max (index, 0),
  1290. GetLengthThatFits (text, width, tabWidth, textDirection)
  1291. )
  1292. );
  1293. }
  1294. /// <summary>
  1295. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1296. /// <c>width</c>. Spaces will not be added to the start or end.
  1297. /// </summary>
  1298. /// <param name="text"></param>
  1299. /// <param name="width"></param>
  1300. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1301. /// <param name="textDirection">The text direction.</param>
  1302. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1303. /// <returns>The justified text.</returns>
  1304. public static string Justify (
  1305. string text,
  1306. int width,
  1307. char spaceChar = ' ',
  1308. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1309. int tabWidth = 0
  1310. )
  1311. {
  1312. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1313. if (string.IsNullOrEmpty (text))
  1314. {
  1315. return text;
  1316. }
  1317. text = ReplaceTABWithSpaces (text, tabWidth);
  1318. string [] words = text.Split (' ');
  1319. int textCount;
  1320. if (IsHorizontalDirection (textDirection))
  1321. {
  1322. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth, textDirection));
  1323. }
  1324. else
  1325. {
  1326. textCount = words.Sum (arg => arg.GetRuneCount ());
  1327. }
  1328. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1329. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1330. var s = new StringBuilder ();
  1331. for (var w = 0; w < words.Length; w++)
  1332. {
  1333. string x = words [w];
  1334. s.Append (x);
  1335. if (w + 1 < words.Length)
  1336. {
  1337. for (var i = 0; i < spaces; i++)
  1338. {
  1339. s.Append (spaceChar);
  1340. }
  1341. }
  1342. if (extras > 0)
  1343. {
  1344. for (var i = 0; i < 1; i++)
  1345. {
  1346. s.Append (spaceChar);
  1347. }
  1348. extras--;
  1349. }
  1350. if (w + 1 == words.Length - 1)
  1351. {
  1352. for (var i = 0; i < extras; i++)
  1353. {
  1354. s.Append (spaceChar);
  1355. }
  1356. }
  1357. }
  1358. return s.ToString ();
  1359. }
  1360. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1361. /// <param name="text"></param>
  1362. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1363. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1364. /// <param name="wordWrap">
  1365. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1366. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1367. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1368. /// </param>
  1369. /// <param name="preserveTrailingSpaces">
  1370. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1371. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1372. /// </param>
  1373. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1374. /// <param name="textDirection">The text direction.</param>
  1375. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1376. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1377. /// <returns>A list of word wrapped lines.</returns>
  1378. /// <remarks>
  1379. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1380. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1381. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1382. /// </remarks>
  1383. public static List<string> Format (
  1384. string text,
  1385. int width,
  1386. Alignment textAlignment,
  1387. bool wordWrap,
  1388. bool preserveTrailingSpaces = false,
  1389. int tabWidth = 0,
  1390. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1391. bool multiLine = false,
  1392. TextFormatter? textFormatter = null
  1393. )
  1394. {
  1395. return Format (
  1396. text,
  1397. width,
  1398. textAlignment == Alignment.Fill,
  1399. wordWrap,
  1400. preserveTrailingSpaces,
  1401. tabWidth,
  1402. textDirection,
  1403. multiLine,
  1404. textFormatter
  1405. );
  1406. }
  1407. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1408. /// <param name="text"></param>
  1409. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1410. /// <param name="justify">Specifies whether the text should be justified.</param>
  1411. /// <param name="wordWrap">
  1412. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1413. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1414. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1415. /// </param>
  1416. /// <param name="preserveTrailingSpaces">
  1417. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1418. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1419. /// </param>
  1420. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1421. /// <param name="textDirection">The text direction.</param>
  1422. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1423. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1424. /// <returns>A list of word wrapped lines.</returns>
  1425. /// <remarks>
  1426. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1427. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1428. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1429. /// </remarks>
  1430. public static List<string> Format (
  1431. string text,
  1432. int width,
  1433. bool justify,
  1434. bool wordWrap,
  1435. bool preserveTrailingSpaces = false,
  1436. int tabWidth = 0,
  1437. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1438. bool multiLine = false,
  1439. TextFormatter? textFormatter = null
  1440. )
  1441. {
  1442. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1443. List<string> lineResult = new ();
  1444. if (string.IsNullOrEmpty (text) || width == 0)
  1445. {
  1446. lineResult.Add (string.Empty);
  1447. return lineResult;
  1448. }
  1449. if (!wordWrap)
  1450. {
  1451. text = ReplaceTABWithSpaces (text, tabWidth);
  1452. if (multiLine)
  1453. {
  1454. // Abhorrent case: Just a new line
  1455. if (text == "\n")
  1456. {
  1457. lineResult.Add (string.Empty);
  1458. return lineResult;
  1459. }
  1460. string []? lines = null;
  1461. if (text.Contains ("\r\n"))
  1462. {
  1463. lines = text.Split ("\r\n");
  1464. }
  1465. else if (text.Contains ('\n'))
  1466. {
  1467. lines = text.Split ('\n');
  1468. }
  1469. lines ??= new [] { text };
  1470. foreach (string line in lines)
  1471. {
  1472. lineResult.Add (
  1473. ClipAndJustify (
  1474. PerformCorrectFormatDirection (textDirection, line),
  1475. width,
  1476. justify,
  1477. textDirection,
  1478. tabWidth,
  1479. textFormatter));
  1480. }
  1481. return PerformCorrectFormatDirection (textDirection, lineResult);
  1482. }
  1483. text = ReplaceCRLFWithSpace (text);
  1484. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1485. return PerformCorrectFormatDirection (textDirection, lineResult);
  1486. }
  1487. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1488. int runeCount = runes.Count;
  1489. var lp = 0;
  1490. for (var i = 0; i < runeCount; i++)
  1491. {
  1492. Rune c = runes [i];
  1493. if (c.Value == '\n')
  1494. {
  1495. List<string> wrappedLines =
  1496. WordWrapText (
  1497. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1498. width,
  1499. preserveTrailingSpaces,
  1500. tabWidth,
  1501. textDirection,
  1502. textFormatter
  1503. );
  1504. foreach (string line in wrappedLines)
  1505. {
  1506. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1507. }
  1508. if (wrappedLines.Count == 0)
  1509. {
  1510. lineResult.Add (string.Empty);
  1511. }
  1512. lp = i + 1;
  1513. }
  1514. }
  1515. foreach (string line in WordWrapText (
  1516. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1517. width,
  1518. preserveTrailingSpaces,
  1519. tabWidth,
  1520. textDirection,
  1521. textFormatter
  1522. ))
  1523. {
  1524. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1525. }
  1526. return PerformCorrectFormatDirection (textDirection, lineResult);
  1527. }
  1528. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1529. {
  1530. return textDirection switch
  1531. {
  1532. TextDirection.RightLeft_BottomTop
  1533. or TextDirection.RightLeft_TopBottom
  1534. or TextDirection.BottomTop_LeftRight
  1535. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1536. _ => line
  1537. };
  1538. }
  1539. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1540. {
  1541. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1542. }
  1543. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1544. {
  1545. return textDirection switch
  1546. {
  1547. TextDirection.TopBottom_RightLeft
  1548. or TextDirection.LeftRight_BottomTop
  1549. or TextDirection.RightLeft_BottomTop
  1550. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1551. _ => lines
  1552. };
  1553. }
  1554. /// <summary>
  1555. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1556. /// </summary>
  1557. /// <remarks>
  1558. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1559. /// glyphs (e.g. Arabic).
  1560. /// </remarks>
  1561. /// <param name="lines">The lines.</param>
  1562. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1563. /// <param name="linesCount">
  1564. /// The number of lines to process (if less than <c>lines.Count</c>, any lines after will be
  1565. /// ignored).
  1566. /// </param>
  1567. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1568. /// <returns>The width required.</returns>
  1569. public static int GetColumnsRequiredForVerticalText (
  1570. List<string> lines,
  1571. int startLine = -1,
  1572. int linesCount = -1,
  1573. int tabWidth = 0
  1574. )
  1575. {
  1576. var max = 0;
  1577. for (int i = startLine == -1 ? 0 : startLine;
  1578. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1579. i++)
  1580. {
  1581. string runes = lines [i];
  1582. if (runes.Length > 0)
  1583. {
  1584. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1585. }
  1586. }
  1587. return max;
  1588. }
  1589. /// <summary>
  1590. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1591. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1592. /// </summary>
  1593. /// <remarks>
  1594. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1595. /// glyphs (e.g. Arabic).
  1596. /// </remarks>
  1597. /// <param name="text">Text, may contain newlines.</param>
  1598. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1599. /// <returns>The length of the longest line.</returns>
  1600. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1601. {
  1602. List<string> result = SplitNewLine (text);
  1603. return result.Max (x => GetRuneWidth (x, tabWidth));
  1604. }
  1605. /// <summary>
  1606. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1607. /// <paramref name="length"/>.
  1608. /// </summary>
  1609. /// <remarks>
  1610. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1611. /// glyphs (e.g. Arabic).
  1612. /// </remarks>
  1613. /// <param name="text">The text.</param>
  1614. /// <param name="startIndex">The start index.</param>
  1615. /// <param name="length">The length.</param>
  1616. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1617. /// <returns>The maximum characters width.</returns>
  1618. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1619. {
  1620. var max = 0;
  1621. Rune [] runes = text.ToRunes ();
  1622. for (int i = startIndex == -1 ? 0 : startIndex;
  1623. i < (length == -1 ? runes.Length : startIndex + length);
  1624. i++)
  1625. {
  1626. max += GetRuneWidth (runes [i], tabWidth);
  1627. }
  1628. return max;
  1629. }
  1630. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</summary>
  1631. /// <remarks>
  1632. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1633. /// glyphs (e.g. Arabic).
  1634. /// </remarks>
  1635. /// <param name="text">The text.</param>
  1636. /// <param name="width">The width.</param>
  1637. /// <param name="tabWidth">The width used for a tab.</param>
  1638. /// <param name="textDirection">The text direction.</param>
  1639. /// <returns>The index of the text that fit the width.</returns>
  1640. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1641. {
  1642. return GetLengthThatFits (text?.ToRuneList () ?? [], width, tabWidth, textDirection);
  1643. }
  1644. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="width"/>.</summary>
  1645. /// <remarks>
  1646. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1647. /// glyphs (e.g. Arabic).
  1648. /// </remarks>
  1649. /// <param name="runes">The list of runes.</param>
  1650. /// <param name="width">The width.</param>
  1651. /// <param name="tabWidth">The width used for a tab.</param>
  1652. /// <param name="textDirection">The text direction.</param>
  1653. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="width"/>.</returns>
  1654. public static int GetLengthThatFits (List<Rune> runes, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1655. {
  1656. if (runes is null || runes.Count == 0)
  1657. {
  1658. return 0;
  1659. }
  1660. var runesLength = 0;
  1661. var runeIdx = 0;
  1662. for (; runeIdx < runes.Count; runeIdx++)
  1663. {
  1664. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth, textDirection);
  1665. if (runesLength + runeWidth > width)
  1666. {
  1667. break;
  1668. }
  1669. runesLength += runeWidth;
  1670. }
  1671. return runeIdx;
  1672. }
  1673. private static int GetRuneWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1674. {
  1675. return GetRuneWidth (str.EnumerateRunes ().ToList (), tabWidth, textDirection);
  1676. }
  1677. private static int GetRuneWidth (List<Rune> runes, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1678. {
  1679. return runes.Sum (r => GetRuneWidth (r, tabWidth, textDirection));
  1680. }
  1681. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1682. {
  1683. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : 1;
  1684. if (rune.Value == '\t')
  1685. {
  1686. return tabWidth;
  1687. }
  1688. if (runeWidth < 0 || runeWidth > 0)
  1689. {
  1690. return Math.Max (runeWidth, 1);
  1691. }
  1692. return runeWidth;
  1693. }
  1694. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  1695. /// <remarks>
  1696. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1697. /// glyphs (e.g. Arabic).
  1698. /// </remarks>
  1699. /// <param name="lines">The lines.</param>
  1700. /// <param name="width">The width.</param>
  1701. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1702. /// <returns>The index of the list that fit the width.</returns>
  1703. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  1704. {
  1705. var runesLength = 0;
  1706. var lineIdx = 0;
  1707. for (; lineIdx < lines.Count; lineIdx++)
  1708. {
  1709. List<Rune> runes = lines [lineIdx].ToRuneList ();
  1710. int maxRruneWidth = runes.Count > 0
  1711. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  1712. : 1;
  1713. if (runesLength + maxRruneWidth > width)
  1714. {
  1715. break;
  1716. }
  1717. runesLength += maxRruneWidth;
  1718. }
  1719. return lineIdx;
  1720. }
  1721. /// <summary>Calculates the rectangle required to hold text, assuming no word wrapping or alignment.</summary>
  1722. /// <remarks>
  1723. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1724. /// glyphs (e.g. Arabic).
  1725. /// </remarks>
  1726. /// <param name="x">The x location of the rectangle</param>
  1727. /// <param name="y">The y location of the rectangle</param>
  1728. /// <param name="text">The text to measure</param>
  1729. /// <param name="direction">The text direction.</param>
  1730. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1731. /// <returns></returns>
  1732. [Obsolete ("CalcRect is deprecated, FormatAndGetSize instead.")]
  1733. internal static Rectangle CalcRect (
  1734. int x,
  1735. int y,
  1736. string text,
  1737. TextDirection direction = TextDirection.LeftRight_TopBottom,
  1738. int tabWidth = 0
  1739. )
  1740. {
  1741. if (string.IsNullOrEmpty (text))
  1742. {
  1743. return new (new (x, y), System.Drawing.Size.Empty);
  1744. }
  1745. int w, h;
  1746. if (IsHorizontalDirection (direction))
  1747. {
  1748. var mw = 0;
  1749. var ml = 1;
  1750. var cols = 0;
  1751. foreach (Rune rune in text.EnumerateRunes ())
  1752. {
  1753. if (rune.Value == '\n')
  1754. {
  1755. ml++;
  1756. if (cols > mw)
  1757. {
  1758. mw = cols;
  1759. }
  1760. cols = 0;
  1761. }
  1762. else if (rune.Value != '\r')
  1763. {
  1764. cols++;
  1765. var rw = 0;
  1766. if (rune.Value == '\t')
  1767. {
  1768. rw += tabWidth - 1;
  1769. }
  1770. else
  1771. {
  1772. rw = rune.GetColumns ();
  1773. if (rw > 0)
  1774. {
  1775. rw--;
  1776. }
  1777. else if (rw == 0)
  1778. {
  1779. cols--;
  1780. }
  1781. }
  1782. cols += rw;
  1783. }
  1784. }
  1785. if (cols > mw)
  1786. {
  1787. mw = cols;
  1788. }
  1789. w = mw;
  1790. h = ml;
  1791. }
  1792. else
  1793. {
  1794. int vw = 1, cw = 1;
  1795. var vh = 0;
  1796. var rows = 0;
  1797. foreach (Rune rune in text.EnumerateRunes ())
  1798. {
  1799. if (rune.Value == '\n')
  1800. {
  1801. vw++;
  1802. if (rows > vh)
  1803. {
  1804. vh = rows;
  1805. }
  1806. rows = 0;
  1807. cw = 1;
  1808. }
  1809. else if (rune.Value != '\r')
  1810. {
  1811. rows++;
  1812. var rw = 0;
  1813. if (rune.Value == '\t')
  1814. {
  1815. rw += tabWidth - 1;
  1816. rows += rw;
  1817. }
  1818. else
  1819. {
  1820. rw = rune.GetColumns ();
  1821. if (rw == 0)
  1822. {
  1823. rows--;
  1824. }
  1825. else if (cw < rw)
  1826. {
  1827. cw = rw;
  1828. vw++;
  1829. }
  1830. }
  1831. }
  1832. }
  1833. if (rows > vh)
  1834. {
  1835. vh = rows;
  1836. }
  1837. w = vw;
  1838. h = vh;
  1839. }
  1840. return new (x, y, w, h);
  1841. }
  1842. /// <summary>Finds the HotKey and its location in text.</summary>
  1843. /// <param name="text">The text to look in.</param>
  1844. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  1845. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  1846. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  1847. /// <param name="firstUpperCase">
  1848. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  1849. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  1850. /// Defaults to <see langword="false"/>.
  1851. /// </param>
  1852. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  1853. public static bool FindHotKey (
  1854. string text,
  1855. Rune hotKeySpecifier,
  1856. out int hotPos,
  1857. out Key hotKey,
  1858. bool firstUpperCase = false
  1859. )
  1860. {
  1861. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  1862. {
  1863. hotPos = -1;
  1864. hotKey = Key.Empty;
  1865. return false;
  1866. }
  1867. var curHotKey = (Rune)0;
  1868. int curHotPos = -1;
  1869. // Use first hot_key char passed into 'hotKey'.
  1870. // TODO: Ignore hot_key of two are provided
  1871. // TODO: Do not support non-alphanumeric chars that can't be typed
  1872. var i = 0;
  1873. foreach (Rune c in text.EnumerateRunes ())
  1874. {
  1875. if ((char)c.Value != 0xFFFD)
  1876. {
  1877. if (c == hotKeySpecifier)
  1878. {
  1879. curHotPos = i;
  1880. }
  1881. else if (curHotPos > -1)
  1882. {
  1883. curHotKey = c;
  1884. break;
  1885. }
  1886. }
  1887. i++;
  1888. }
  1889. // Legacy support - use first upper case char if the specifier was not found
  1890. if (curHotPos == -1 && firstUpperCase)
  1891. {
  1892. i = 0;
  1893. foreach (Rune c in text.EnumerateRunes ())
  1894. {
  1895. if ((char)c.Value != 0xFFFD)
  1896. {
  1897. if (Rune.IsUpper (c))
  1898. {
  1899. curHotKey = c;
  1900. curHotPos = i;
  1901. break;
  1902. }
  1903. }
  1904. i++;
  1905. }
  1906. }
  1907. if (curHotKey != (Rune)0 && curHotPos != -1)
  1908. {
  1909. hotPos = curHotPos;
  1910. var newHotKey = (KeyCode)curHotKey.Value;
  1911. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  1912. {
  1913. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  1914. {
  1915. newHotKey &= ~KeyCode.Space;
  1916. }
  1917. hotKey = newHotKey;
  1918. //hotKey.Scope = KeyBindingScope.HotKey;
  1919. return true;
  1920. }
  1921. }
  1922. hotPos = -1;
  1923. hotKey = KeyCode.Null;
  1924. return false;
  1925. }
  1926. /// <summary>
  1927. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  1928. /// hotkey.
  1929. /// </summary>
  1930. /// <param name="text">The text to tag the hotkey in.</param>
  1931. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1932. /// <returns>The text with the hotkey tagged.</returns>
  1933. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  1934. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  1935. {
  1936. // Set the high bit
  1937. List<Rune> runes = text.ToRuneList ();
  1938. if (Rune.IsLetterOrDigit (runes [hotPos]))
  1939. {
  1940. runes [hotPos] = new ((uint)runes [hotPos].Value);
  1941. }
  1942. return StringExtensions.ToString (runes);
  1943. }
  1944. /// <summary>Removes the hotkey specifier from text.</summary>
  1945. /// <param name="text">The text to manipulate.</param>
  1946. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1947. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1948. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1949. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  1950. {
  1951. if (string.IsNullOrEmpty (text))
  1952. {
  1953. return text;
  1954. }
  1955. // Scan
  1956. var start = string.Empty;
  1957. var i = 0;
  1958. foreach (Rune c in text)
  1959. {
  1960. if (c == hotKeySpecifier && i == hotPos)
  1961. {
  1962. i++;
  1963. continue;
  1964. }
  1965. start += c;
  1966. i++;
  1967. }
  1968. return start;
  1969. }
  1970. #endregion // Static Members
  1971. }