TextFormatter.cs 76 KB

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