TextFormatter.cs 77 KB

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