TextFormatter.cs 78 KB

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