TextFormatter.cs 70 KB

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