TextFormatter.cs 77 KB

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