TextFormatter.cs 82 KB

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