TextFormatter.cs 78 KB

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