TextFormatter.cs 77 KB

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