TextFormatter.cs 98 KB

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