TextFormatter.cs 79 KB

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