TextFormatter.cs 73 KB

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