TextFormatter.cs 74 KB

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