TextFormatter.cs 75 KB

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