TextFormatter.cs 77 KB

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