TextFormatter.cs 77 KB

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