TextFormatter.cs 74 KB

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