TextFormatter.cs 77 KB

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