TextFormatter.cs 76 KB

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