TextFormatter.cs 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  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 = lines.Max (static line => line.GetColumns ());
  588. int height = lines.Count;
  589. if (IsVerticalDirection (Direction))
  590. {
  591. return new (height, width);
  592. }
  593. return new (width, height);
  594. }
  595. /// <summary>Gets a list of formatted lines, constrained to <see cref="Size"/>.</summary>
  596. /// <remarks>
  597. /// <para>
  598. /// If the text needs to be formatted (if <see cref="NeedsFormat"/> is <see langword="true"/>)
  599. /// <see cref="Format()"/> will be called and upon return
  600. /// <see cref="NeedsFormat"/> will be <see langword="false"/>.
  601. /// </para>
  602. /// <para>
  603. /// If either of the dimensions of <see cref="Size"/> are zero, the text will not be formatted and no lines will
  604. /// be returned.
  605. /// </para>
  606. /// </remarks>
  607. public List<string> GetLines ()
  608. {
  609. // With this check, we protect against subclasses with overrides of Text
  610. if (string.IsNullOrEmpty (Text) || Size.Height == 0 || Size.Width == 0)
  611. {
  612. _lines = new List<string> { string.Empty };
  613. NeedsFormat = false;
  614. return _lines;
  615. }
  616. if (NeedsFormat)
  617. {
  618. string text = _text;
  619. if (FindHotKey (_text, HotKeySpecifier, out _hotKeyPos, out Key newHotKey))
  620. {
  621. HotKey = newHotKey;
  622. text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  623. text = ReplaceHotKeyWithTag (text, _hotKeyPos);
  624. }
  625. if (IsVerticalDirection (Direction))
  626. {
  627. int colsWidth = GetSumMaxCharWidth (text, 0, 1, TabWidth);
  628. _lines = Format (
  629. text,
  630. Size.Height,
  631. VerticalAlignment == Alignment.Fill,
  632. Size.Width > colsWidth && WordWrap,
  633. PreserveTrailingSpaces,
  634. TabWidth,
  635. Direction,
  636. MultiLine,
  637. this
  638. );
  639. if (!AutoSize)
  640. {
  641. colsWidth = GetMaxColsForWidth (_lines, Size.Width, TabWidth);
  642. if (_lines.Count > colsWidth)
  643. {
  644. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  645. }
  646. }
  647. }
  648. else
  649. {
  650. _lines = Format (
  651. text,
  652. Size.Width,
  653. Alignment == Alignment.Fill,
  654. Size.Height > 1 && WordWrap,
  655. PreserveTrailingSpaces,
  656. TabWidth,
  657. Direction,
  658. MultiLine,
  659. this
  660. );
  661. if (!AutoSize && _lines.Count > Size.Height)
  662. {
  663. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  664. }
  665. }
  666. NeedsFormat = false;
  667. }
  668. return _lines;
  669. }
  670. /// <summary>Event invoked when the <see cref="HotKey"/> is changed.</summary>
  671. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  672. /// <summary>Sets <see cref="NeedsFormat"/> to <see langword="true"/> and returns the value.</summary>
  673. /// <typeparam name="T"></typeparam>
  674. /// <param name="value"></param>
  675. /// <returns></returns>
  676. private T EnableNeedsFormat<T> (T value)
  677. {
  678. NeedsFormat = true;
  679. return value;
  680. }
  681. #region Static Members
  682. /// <summary>Check if it is a horizontal direction</summary>
  683. public static bool IsHorizontalDirection (TextDirection textDirection)
  684. {
  685. return textDirection switch
  686. {
  687. TextDirection.LeftRight_TopBottom => true,
  688. TextDirection.LeftRight_BottomTop => true,
  689. TextDirection.RightLeft_TopBottom => true,
  690. TextDirection.RightLeft_BottomTop => true,
  691. _ => false
  692. };
  693. }
  694. /// <summary>Check if it is a vertical direction</summary>
  695. public static bool IsVerticalDirection (TextDirection textDirection)
  696. {
  697. return textDirection switch
  698. {
  699. TextDirection.TopBottom_LeftRight => true,
  700. TextDirection.TopBottom_RightLeft => true,
  701. TextDirection.BottomTop_LeftRight => true,
  702. TextDirection.BottomTop_RightLeft => true,
  703. _ => false
  704. };
  705. }
  706. /// <summary>Check if it is Left to Right direction</summary>
  707. public static bool IsLeftToRight (TextDirection textDirection)
  708. {
  709. return textDirection switch
  710. {
  711. TextDirection.LeftRight_TopBottom => true,
  712. TextDirection.LeftRight_BottomTop => true,
  713. _ => false
  714. };
  715. }
  716. /// <summary>Check if it is Top to Bottom direction</summary>
  717. public static bool IsTopToBottom (TextDirection textDirection)
  718. {
  719. return textDirection switch
  720. {
  721. TextDirection.TopBottom_LeftRight => true,
  722. TextDirection.TopBottom_RightLeft => true,
  723. _ => false
  724. };
  725. }
  726. // TODO: Move to StringExtensions?
  727. private static string StripCRLF (string str, bool keepNewLine = false)
  728. {
  729. List<Rune> runes = str.ToRuneList ();
  730. for (var i = 0; i < runes.Count; i++)
  731. {
  732. switch ((char)runes [i].Value)
  733. {
  734. case '\n':
  735. if (!keepNewLine)
  736. {
  737. runes.RemoveAt (i);
  738. }
  739. break;
  740. case '\r':
  741. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  742. {
  743. runes.RemoveAt (i);
  744. if (!keepNewLine)
  745. {
  746. runes.RemoveAt (i);
  747. }
  748. i++;
  749. }
  750. else
  751. {
  752. if (!keepNewLine)
  753. {
  754. runes.RemoveAt (i);
  755. }
  756. }
  757. break;
  758. }
  759. }
  760. return StringExtensions.ToString (runes);
  761. }
  762. // TODO: Move to StringExtensions?
  763. private static string ReplaceCRLFWithSpace (string str)
  764. {
  765. List<Rune> runes = str.ToRuneList ();
  766. for (var i = 0; i < runes.Count; i++)
  767. {
  768. switch (runes [i].Value)
  769. {
  770. case '\n':
  771. runes [i] = (Rune)' ';
  772. break;
  773. case '\r':
  774. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  775. {
  776. runes [i] = (Rune)' ';
  777. runes.RemoveAt (i + 1);
  778. i++;
  779. }
  780. else
  781. {
  782. runes [i] = (Rune)' ';
  783. }
  784. break;
  785. }
  786. }
  787. return StringExtensions.ToString (runes);
  788. }
  789. // TODO: Move to StringExtensions?
  790. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  791. {
  792. if (tabWidth == 0)
  793. {
  794. return str.Replace ("\t", "");
  795. }
  796. return str.Replace ("\t", new string (' ', tabWidth));
  797. }
  798. // TODO: Move to StringExtensions?
  799. /// <summary>
  800. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  801. /// ending newline.
  802. /// </summary>
  803. /// <param name="text">The text.</param>
  804. /// <returns>A list of text without the newline characters.</returns>
  805. public static List<string> SplitNewLine (string text)
  806. {
  807. List<Rune> runes = text.ToRuneList ();
  808. List<string> lines = new ();
  809. var start = 0;
  810. for (var i = 0; i < runes.Count; i++)
  811. {
  812. int end = i;
  813. switch (runes [i].Value)
  814. {
  815. case '\n':
  816. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  817. i++;
  818. start = i;
  819. break;
  820. case '\r':
  821. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  822. {
  823. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  824. i += 2;
  825. start = i;
  826. }
  827. else
  828. {
  829. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  830. i++;
  831. start = i;
  832. }
  833. break;
  834. }
  835. }
  836. switch (runes.Count)
  837. {
  838. case > 0 when lines.Count == 0:
  839. lines.Add (StringExtensions.ToString (runes));
  840. break;
  841. case > 0 when start < runes.Count:
  842. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  843. break;
  844. default:
  845. lines.Add ("");
  846. break;
  847. }
  848. return lines;
  849. }
  850. // TODO: Move to StringExtensions?
  851. /// <summary>
  852. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  853. /// columns. Note that some unicode characters take 2+ columns
  854. /// </summary>
  855. /// <param name="text"></param>
  856. /// <param name="width"></param>
  857. /// <returns></returns>
  858. public static string ClipOrPad (string text, int width)
  859. {
  860. if (string.IsNullOrEmpty (text))
  861. {
  862. return text;
  863. }
  864. // if value is not wide enough
  865. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  866. {
  867. // pad it out with spaces to the given Alignment
  868. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  869. return text + new string (' ', toPad);
  870. }
  871. // value is too wide
  872. return new string (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  873. }
  874. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  875. /// <param name="text">The text to word wrap</param>
  876. /// <param name="width">The number of columns to constrain the text to</param>
  877. /// <param name="preserveTrailingSpaces">
  878. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  879. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  880. /// </param>
  881. /// <param name="tabWidth">The number of columns used for a tab.</param>
  882. /// <param name="textDirection">The text direction.</param>
  883. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  884. /// <returns>A list of word wrapped lines.</returns>
  885. /// <remarks>
  886. /// <para>This method does not do any alignment.</para>
  887. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  888. /// <para>
  889. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  890. /// at the end of the last line.
  891. /// </para>
  892. /// </remarks>
  893. /// <returns>A list of lines.</returns>
  894. public static List<string> WordWrapText (
  895. string text,
  896. int width,
  897. bool preserveTrailingSpaces = false,
  898. int tabWidth = 0,
  899. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  900. TextFormatter textFormatter = null
  901. )
  902. {
  903. if (width < 0)
  904. {
  905. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  906. }
  907. List<string> lines = new ();
  908. if (string.IsNullOrEmpty (text))
  909. {
  910. return lines;
  911. }
  912. List<Rune> runes = StripCRLF (text).ToRuneList ();
  913. int start = Math.Max (
  914. !runes.Contains ((Rune)' ') && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  915. ? runes.Count - width
  916. : 0,
  917. 0);
  918. int end;
  919. if (preserveTrailingSpaces)
  920. {
  921. while ((end = start) < runes.Count)
  922. {
  923. end = GetNextWhiteSpace (start, width, out bool incomplete);
  924. if (end == 0 && incomplete)
  925. {
  926. start = text.GetRuneCount ();
  927. break;
  928. }
  929. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  930. start = end;
  931. if (incomplete)
  932. {
  933. start = text.GetRuneCount ();
  934. break;
  935. }
  936. }
  937. }
  938. else
  939. {
  940. if (IsHorizontalDirection (textDirection))
  941. {
  942. while ((end = start
  943. + GetLengthThatFits (
  944. runes.GetRange (start, runes.Count - start),
  945. width,
  946. tabWidth,
  947. textDirection
  948. ))
  949. < runes.Count)
  950. {
  951. while (runes [end].Value != ' ' && end > start)
  952. {
  953. end--;
  954. }
  955. if (end == start)
  956. {
  957. end = start
  958. + GetLengthThatFits (
  959. runes.GetRange (end, runes.Count - end),
  960. width,
  961. tabWidth,
  962. textDirection
  963. );
  964. }
  965. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  966. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  967. if (end > start && GetRuneWidth (str, tabWidth, textDirection) <= width + zeroLength)
  968. {
  969. lines.Add (str);
  970. start = end;
  971. if (runes [end].Value == ' ')
  972. {
  973. start++;
  974. }
  975. }
  976. else
  977. {
  978. end++;
  979. start = end;
  980. }
  981. }
  982. }
  983. else
  984. {
  985. while ((end = start + width) < runes.Count)
  986. {
  987. while (runes [end].Value != ' ' && end > start)
  988. {
  989. end--;
  990. }
  991. if (end == start)
  992. {
  993. end = start + width;
  994. }
  995. var zeroLength = 0;
  996. for (int i = end; i < runes.Count - start; i++)
  997. {
  998. Rune r = runes [i];
  999. if (r.GetColumns () == 0)
  1000. {
  1001. zeroLength++;
  1002. }
  1003. else
  1004. {
  1005. break;
  1006. }
  1007. }
  1008. lines.Add (
  1009. StringExtensions.ToString (
  1010. runes.GetRange (
  1011. start,
  1012. end - start + zeroLength
  1013. )
  1014. )
  1015. );
  1016. end += zeroLength;
  1017. start = end;
  1018. if (runes [end].Value == ' ')
  1019. {
  1020. start++;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1026. {
  1027. int to = from;
  1028. int length = cLength;
  1029. incomplete = false;
  1030. while (length < cWidth && to < runes.Count)
  1031. {
  1032. Rune rune = runes [to];
  1033. if (IsHorizontalDirection (textDirection))
  1034. {
  1035. length += rune.GetColumns ();
  1036. }
  1037. else
  1038. {
  1039. length++;
  1040. }
  1041. if (length > cWidth)
  1042. {
  1043. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1044. {
  1045. incomplete = true;
  1046. }
  1047. return to;
  1048. }
  1049. switch (rune.Value)
  1050. {
  1051. case ' ' when length == cWidth:
  1052. return to + 1;
  1053. case ' ' when length > cWidth:
  1054. return to;
  1055. case ' ':
  1056. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1057. case '\t':
  1058. {
  1059. length += tabWidth + 1;
  1060. if (length == tabWidth && tabWidth > cWidth)
  1061. {
  1062. return to + 1;
  1063. }
  1064. if (length > cWidth && tabWidth > cWidth)
  1065. {
  1066. return to;
  1067. }
  1068. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1069. }
  1070. default:
  1071. to++;
  1072. break;
  1073. }
  1074. }
  1075. return cLength switch
  1076. {
  1077. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1078. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1079. _ => to
  1080. };
  1081. }
  1082. if (start < text.GetRuneCount ())
  1083. {
  1084. string str = ReplaceTABWithSpaces (
  1085. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1086. tabWidth
  1087. );
  1088. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1089. {
  1090. lines.Add (str);
  1091. }
  1092. }
  1093. return lines;
  1094. }
  1095. /// <summary>Justifies text within a specified width.</summary>
  1096. /// <param name="text">The text to justify.</param>
  1097. /// <param name="width">
  1098. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1099. /// clipped.
  1100. /// </param>
  1101. /// <param name="textAlignment">Alignment.</param>
  1102. /// <param name="textDirection">The text direction.</param>
  1103. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1104. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1105. /// <returns>Justified and clipped text.</returns>
  1106. public static string ClipAndJustify (
  1107. string text,
  1108. int width,
  1109. Alignment textAlignment,
  1110. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1111. int tabWidth = 0,
  1112. TextFormatter textFormatter = null
  1113. )
  1114. {
  1115. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  1116. }
  1117. /// <summary>Justifies text within a specified width.</summary>
  1118. /// <param name="text">The text to justify.</param>
  1119. /// <param name="width">
  1120. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1121. /// clipped.
  1122. /// </param>
  1123. /// <param name="justify">Justify.</param>
  1124. /// <param name="textDirection">The text direction.</param>
  1125. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1126. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1127. /// <returns>Justified and clipped text.</returns>
  1128. public static string ClipAndJustify (
  1129. string text,
  1130. int width,
  1131. bool justify,
  1132. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1133. int tabWidth = 0,
  1134. TextFormatter textFormatter = null
  1135. )
  1136. {
  1137. if (width < 0)
  1138. {
  1139. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1140. }
  1141. if (string.IsNullOrEmpty (text))
  1142. {
  1143. return text;
  1144. }
  1145. text = ReplaceTABWithSpaces (text, tabWidth);
  1146. List<Rune> runes = text.ToRuneList ();
  1147. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1148. if (runes.Count - zeroLength > width)
  1149. {
  1150. if (IsHorizontalDirection (textDirection))
  1151. {
  1152. if (textFormatter is { Alignment: Alignment.End })
  1153. {
  1154. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1155. }
  1156. if (textFormatter is { Alignment: Alignment.Center })
  1157. {
  1158. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1159. }
  1160. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1161. }
  1162. if (IsVerticalDirection (textDirection))
  1163. {
  1164. if (textFormatter is { VerticalAlignment: Alignment.End })
  1165. {
  1166. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1167. }
  1168. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1169. {
  1170. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1171. }
  1172. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1173. }
  1174. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1175. }
  1176. if (justify)
  1177. {
  1178. return Justify (text, width, ' ', textDirection, tabWidth);
  1179. }
  1180. if (IsHorizontalDirection (textDirection))
  1181. {
  1182. if (textFormatter is { Alignment: Alignment.End })
  1183. {
  1184. if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1185. {
  1186. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1187. }
  1188. }
  1189. else if (textFormatter is { Alignment: Alignment.Center })
  1190. {
  1191. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1192. }
  1193. else if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1194. {
  1195. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1196. }
  1197. }
  1198. if (IsVerticalDirection (textDirection))
  1199. {
  1200. if (textFormatter is { VerticalAlignment: Alignment.End })
  1201. {
  1202. if (runes.Count - zeroLength > width)
  1203. {
  1204. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1205. }
  1206. }
  1207. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1208. {
  1209. return GetRangeThatFits (runes, Math.Max ((runes.Count - width) / 2, 0), text, width, tabWidth, textDirection);
  1210. }
  1211. else if (runes.Count - zeroLength > width)
  1212. {
  1213. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1214. }
  1215. }
  1216. return text;
  1217. }
  1218. private static string GetRangeThatFits (List<Rune> runes, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1219. {
  1220. return StringExtensions.ToString (
  1221. runes.GetRange (
  1222. Math.Max (index, 0),
  1223. GetLengthThatFits (text, width, tabWidth, textDirection)
  1224. )
  1225. );
  1226. }
  1227. /// <summary>
  1228. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1229. /// <c>width</c>. Spaces will not be added to the start or end.
  1230. /// </summary>
  1231. /// <param name="text"></param>
  1232. /// <param name="width"></param>
  1233. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1234. /// <param name="textDirection">The text direction.</param>
  1235. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1236. /// <returns>The justified text.</returns>
  1237. public static string Justify (
  1238. string text,
  1239. int width,
  1240. char spaceChar = ' ',
  1241. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1242. int tabWidth = 0
  1243. )
  1244. {
  1245. if (width < 0)
  1246. {
  1247. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1248. }
  1249. if (string.IsNullOrEmpty (text))
  1250. {
  1251. return text;
  1252. }
  1253. text = ReplaceTABWithSpaces (text, tabWidth);
  1254. string [] words = text.Split (' ');
  1255. int textCount;
  1256. if (IsHorizontalDirection (textDirection))
  1257. {
  1258. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth, textDirection));
  1259. }
  1260. else
  1261. {
  1262. textCount = words.Sum (arg => arg.GetRuneCount ());
  1263. }
  1264. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1265. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1266. var s = new StringBuilder ();
  1267. for (var w = 0; w < words.Length; w++)
  1268. {
  1269. string x = words [w];
  1270. s.Append (x);
  1271. if (w + 1 < words.Length)
  1272. {
  1273. for (var i = 0; i < spaces; i++)
  1274. {
  1275. s.Append (spaceChar);
  1276. }
  1277. }
  1278. if (extras > 0)
  1279. {
  1280. for (var i = 0; i < 1; i++)
  1281. {
  1282. s.Append (spaceChar);
  1283. }
  1284. extras--;
  1285. }
  1286. if (w + 1 == words.Length - 1)
  1287. {
  1288. for (var i = 0; i < extras; i++)
  1289. {
  1290. s.Append (spaceChar);
  1291. }
  1292. }
  1293. }
  1294. return s.ToString ();
  1295. }
  1296. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1297. /// <param name="text"></param>
  1298. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1299. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1300. /// <param name="wordWrap">
  1301. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1302. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1303. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1304. /// </param>
  1305. /// <param name="preserveTrailingSpaces">
  1306. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1307. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1308. /// </param>
  1309. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1310. /// <param name="textDirection">The text direction.</param>
  1311. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1312. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1313. /// <returns>A list of word wrapped lines.</returns>
  1314. /// <remarks>
  1315. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1316. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1317. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1318. /// </remarks>
  1319. public static List<string> Format (
  1320. string text,
  1321. int width,
  1322. Alignment textAlignment,
  1323. bool wordWrap,
  1324. bool preserveTrailingSpaces = false,
  1325. int tabWidth = 0,
  1326. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1327. bool multiLine = false,
  1328. TextFormatter textFormatter = null
  1329. )
  1330. {
  1331. return Format (
  1332. text,
  1333. width,
  1334. textAlignment == Alignment.Fill,
  1335. wordWrap,
  1336. preserveTrailingSpaces,
  1337. tabWidth,
  1338. textDirection,
  1339. multiLine,
  1340. textFormatter
  1341. );
  1342. }
  1343. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1344. /// <param name="text"></param>
  1345. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1346. /// <param name="justify">Specifies whether the text should be justified.</param>
  1347. /// <param name="wordWrap">
  1348. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1349. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1350. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1351. /// </param>
  1352. /// <param name="preserveTrailingSpaces">
  1353. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1354. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1355. /// </param>
  1356. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1357. /// <param name="textDirection">The text direction.</param>
  1358. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1359. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1360. /// <returns>A list of word wrapped lines.</returns>
  1361. /// <remarks>
  1362. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1363. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1364. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1365. /// </remarks>
  1366. public static List<string> Format (
  1367. string text,
  1368. int width,
  1369. bool justify,
  1370. bool wordWrap,
  1371. bool preserveTrailingSpaces = false,
  1372. int tabWidth = 0,
  1373. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1374. bool multiLine = false,
  1375. TextFormatter textFormatter = null
  1376. )
  1377. {
  1378. if (width < 0)
  1379. {
  1380. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1381. }
  1382. List<string> lineResult = new ();
  1383. if (string.IsNullOrEmpty (text) || width == 0)
  1384. {
  1385. lineResult.Add (string.Empty);
  1386. return lineResult;
  1387. }
  1388. if (!wordWrap)
  1389. {
  1390. text = ReplaceTABWithSpaces (text, tabWidth);
  1391. if (multiLine)
  1392. {
  1393. // Abhorrent case: Just a new line
  1394. if (text == "\n")
  1395. {
  1396. lineResult.Add (string.Empty);
  1397. return lineResult;
  1398. }
  1399. string [] lines = null;
  1400. if (text.Contains ("\r\n"))
  1401. {
  1402. lines = text.Split ("\r\n");
  1403. }
  1404. else if (text.Contains ('\n'))
  1405. {
  1406. lines = text.Split ('\n');
  1407. }
  1408. lines ??= new [] { text };
  1409. foreach (string line in lines)
  1410. {
  1411. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, line), width, justify, textDirection, tabWidth, textFormatter));
  1412. }
  1413. return PerformCorrectFormatDirection (textDirection, lineResult);
  1414. }
  1415. text = ReplaceCRLFWithSpace (text);
  1416. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1417. return PerformCorrectFormatDirection (textDirection, lineResult);
  1418. }
  1419. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1420. int runeCount = runes.Count;
  1421. var lp = 0;
  1422. for (var i = 0; i < runeCount; i++)
  1423. {
  1424. Rune c = runes [i];
  1425. if (c.Value == '\n')
  1426. {
  1427. List<string> wrappedLines =
  1428. WordWrapText (
  1429. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1430. width,
  1431. preserveTrailingSpaces,
  1432. tabWidth,
  1433. textDirection,
  1434. textFormatter
  1435. );
  1436. foreach (string line in wrappedLines)
  1437. {
  1438. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1439. }
  1440. if (wrappedLines.Count == 0)
  1441. {
  1442. lineResult.Add (string.Empty);
  1443. }
  1444. lp = i + 1;
  1445. }
  1446. }
  1447. foreach (string line in WordWrapText (
  1448. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1449. width,
  1450. preserveTrailingSpaces,
  1451. tabWidth,
  1452. textDirection,
  1453. textFormatter
  1454. ))
  1455. {
  1456. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1457. }
  1458. return PerformCorrectFormatDirection (textDirection, lineResult);
  1459. }
  1460. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1461. {
  1462. return textDirection switch
  1463. {
  1464. TextDirection.RightLeft_BottomTop
  1465. or TextDirection.RightLeft_TopBottom
  1466. or TextDirection.BottomTop_LeftRight
  1467. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1468. _ => line
  1469. };
  1470. }
  1471. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1472. {
  1473. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1474. }
  1475. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1476. {
  1477. return textDirection switch
  1478. {
  1479. TextDirection.TopBottom_RightLeft
  1480. or TextDirection.LeftRight_BottomTop
  1481. or TextDirection.RightLeft_BottomTop
  1482. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1483. _ => lines
  1484. };
  1485. }
  1486. /// <summary>Returns the number of lines needed to render the specified text given the width.</summary>
  1487. /// <remarks>Calls <see cref="Format()"/>.</remarks>
  1488. /// <returns>Number of lines.</returns>
  1489. /// <param name="text">Text, may contain newlines.</param>
  1490. /// <param name="width">The minimum width for the text.</param>
  1491. public static int GetLineCount (string text, int width)
  1492. {
  1493. List<string> result = Format (text, width, false, true);
  1494. return result.Count;
  1495. }
  1496. /// <summary>
  1497. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1498. /// </summary>
  1499. /// <remarks>
  1500. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1501. /// glyphs (e.g. Arabic).
  1502. /// </remarks>
  1503. /// <param name="lines">The lines.</param>
  1504. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1505. /// <param name="linesCount">The number of lines to process (if less than <c>lines.Count</c>, any lines after will be ignored).</param>
  1506. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1507. /// <returns>The width required.</returns>
  1508. public static int GetColumnsRequiredForVerticalText (
  1509. List<string> lines,
  1510. int startLine = -1,
  1511. int linesCount = -1,
  1512. int tabWidth = 0
  1513. )
  1514. {
  1515. var max = 0;
  1516. for (int i = startLine == -1 ? 0 : startLine;
  1517. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1518. i++)
  1519. {
  1520. string runes = lines [i];
  1521. if (runes.Length > 0)
  1522. {
  1523. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1524. }
  1525. }
  1526. return max;
  1527. }
  1528. /// <summary>
  1529. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1530. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1531. /// </summary>
  1532. /// <remarks>
  1533. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1534. /// glyphs (e.g. Arabic).
  1535. /// </remarks>
  1536. /// <param name="text">Text, may contain newlines.</param>
  1537. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1538. /// <returns>The length of the longest line.</returns>
  1539. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1540. {
  1541. List<string> result = SplitNewLine (text);
  1542. return result.Max (x => GetRuneWidth (x, tabWidth));
  1543. }
  1544. /// <summary>
  1545. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1546. /// <paramref name="length"/>.
  1547. /// </summary>
  1548. /// <remarks>
  1549. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1550. /// glyphs (e.g. Arabic).
  1551. /// </remarks>
  1552. /// <param name="text">The text.</param>
  1553. /// <param name="startIndex">The start index.</param>
  1554. /// <param name="length">The length.</param>
  1555. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1556. /// <returns>The maximum characters width.</returns>
  1557. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1558. {
  1559. var max = 0;
  1560. Rune [] runes = text.ToRunes ();
  1561. for (int i = startIndex == -1 ? 0 : startIndex;
  1562. i < (length == -1 ? runes.Length : startIndex + length);
  1563. i++)
  1564. {
  1565. max += GetRuneWidth (runes [i], tabWidth);
  1566. }
  1567. return max;
  1568. }
  1569. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</summary>
  1570. /// <remarks>
  1571. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1572. /// glyphs (e.g. Arabic).
  1573. /// </remarks>
  1574. /// <param name="text">The text.</param>
  1575. /// <param name="width">The width.</param>
  1576. /// <param name="tabWidth">The width used for a tab.</param>
  1577. /// <param name="textDirection">The text direction.</param>
  1578. /// <returns>The index of the text that fit the width.</returns>
  1579. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1580. {
  1581. return GetLengthThatFits (text?.ToRuneList (), width, tabWidth, textDirection);
  1582. }
  1583. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="width"/>.</summary>
  1584. /// <remarks>
  1585. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1586. /// glyphs (e.g. Arabic).
  1587. /// </remarks>
  1588. /// <param name="runes">The list of runes.</param>
  1589. /// <param name="width">The width.</param>
  1590. /// <param name="tabWidth">The width used for a tab.</param>
  1591. /// <param name="textDirection">The text direction.</param>
  1592. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="width"/>.</returns>
  1593. public static int GetLengthThatFits (List<Rune> runes, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1594. {
  1595. if (runes is null || runes.Count == 0)
  1596. {
  1597. return 0;
  1598. }
  1599. var runesLength = 0;
  1600. var runeIdx = 0;
  1601. for (; runeIdx < runes.Count; runeIdx++)
  1602. {
  1603. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth, textDirection);
  1604. if (runesLength + runeWidth > width)
  1605. {
  1606. break;
  1607. }
  1608. runesLength += runeWidth;
  1609. }
  1610. return runeIdx;
  1611. }
  1612. private static int GetRuneWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom) { return GetRuneWidth (str.EnumerateRunes ().ToList (), tabWidth, textDirection); }
  1613. private static int GetRuneWidth (List<Rune> runes, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom) { return runes.Sum (r => GetRuneWidth (r, tabWidth, textDirection)); }
  1614. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1615. {
  1616. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : 1;
  1617. if (rune.Value == '\t')
  1618. {
  1619. return tabWidth;
  1620. }
  1621. if (runeWidth < 0 || runeWidth > 0)
  1622. {
  1623. return Math.Max (runeWidth, 1);
  1624. }
  1625. return runeWidth;
  1626. }
  1627. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  1628. /// <remarks>
  1629. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1630. /// glyphs (e.g. Arabic).
  1631. /// </remarks>
  1632. /// <param name="lines">The lines.</param>
  1633. /// <param name="width">The width.</param>
  1634. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1635. /// <returns>The index of the list that fit the width.</returns>
  1636. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  1637. {
  1638. var runesLength = 0;
  1639. var lineIdx = 0;
  1640. for (; lineIdx < lines.Count; lineIdx++)
  1641. {
  1642. List<Rune> runes = lines [lineIdx].ToRuneList ();
  1643. int maxRruneWidth = runes.Count > 0
  1644. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  1645. : 1;
  1646. if (runesLength + maxRruneWidth > width)
  1647. {
  1648. break;
  1649. }
  1650. runesLength += maxRruneWidth;
  1651. }
  1652. return lineIdx;
  1653. }
  1654. /// <summary>Calculates the rectangle required to hold text, assuming no word wrapping or alignment.</summary>
  1655. /// <remarks>
  1656. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1657. /// glyphs (e.g. Arabic).
  1658. /// </remarks>
  1659. /// <param name="x">The x location of the rectangle</param>
  1660. /// <param name="y">The y location of the rectangle</param>
  1661. /// <param name="text">The text to measure</param>
  1662. /// <param name="direction">The text direction.</param>
  1663. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1664. /// <returns></returns>
  1665. public static Rectangle CalcRect (
  1666. int x,
  1667. int y,
  1668. string text,
  1669. TextDirection direction = TextDirection.LeftRight_TopBottom,
  1670. int tabWidth = 0
  1671. )
  1672. {
  1673. if (string.IsNullOrEmpty (text))
  1674. {
  1675. return new (new (x, y), Size.Empty);
  1676. }
  1677. int w, h;
  1678. if (IsHorizontalDirection (direction))
  1679. {
  1680. var mw = 0;
  1681. var ml = 1;
  1682. var cols = 0;
  1683. foreach (Rune rune in text.EnumerateRunes ())
  1684. {
  1685. if (rune.Value == '\n')
  1686. {
  1687. ml++;
  1688. if (cols > mw)
  1689. {
  1690. mw = cols;
  1691. }
  1692. cols = 0;
  1693. }
  1694. else if (rune.Value != '\r')
  1695. {
  1696. cols++;
  1697. var rw = 0;
  1698. if (rune.Value == '\t')
  1699. {
  1700. rw += tabWidth - 1;
  1701. }
  1702. else
  1703. {
  1704. rw = rune.GetColumns ();
  1705. if (rw > 0)
  1706. {
  1707. rw--;
  1708. }
  1709. else if (rw == 0)
  1710. {
  1711. cols--;
  1712. }
  1713. }
  1714. cols += rw;
  1715. }
  1716. }
  1717. if (cols > mw)
  1718. {
  1719. mw = cols;
  1720. }
  1721. w = mw;
  1722. h = ml;
  1723. }
  1724. else
  1725. {
  1726. int vw = 1, cw = 1;
  1727. var vh = 0;
  1728. var rows = 0;
  1729. foreach (Rune rune in text.EnumerateRunes ())
  1730. {
  1731. if (rune.Value == '\n')
  1732. {
  1733. vw++;
  1734. if (rows > vh)
  1735. {
  1736. vh = rows;
  1737. }
  1738. rows = 0;
  1739. cw = 1;
  1740. }
  1741. else if (rune.Value != '\r')
  1742. {
  1743. rows++;
  1744. var rw = 0;
  1745. if (rune.Value == '\t')
  1746. {
  1747. rw += tabWidth - 1;
  1748. rows += rw;
  1749. }
  1750. else
  1751. {
  1752. rw = rune.GetColumns ();
  1753. if (rw == 0)
  1754. {
  1755. rows--;
  1756. }
  1757. else if (cw < rw)
  1758. {
  1759. cw = rw;
  1760. vw++;
  1761. }
  1762. }
  1763. }
  1764. }
  1765. if (rows > vh)
  1766. {
  1767. vh = rows;
  1768. }
  1769. w = vw;
  1770. h = vh;
  1771. }
  1772. return new (x, y, w, h);
  1773. }
  1774. /// <summary>Finds the HotKey and its location in text.</summary>
  1775. /// <param name="text">The text to look in.</param>
  1776. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  1777. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  1778. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  1779. /// <param name="firstUpperCase">
  1780. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  1781. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  1782. /// Defaults to <see langword="false"/>.
  1783. /// </param>
  1784. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  1785. public static bool FindHotKey (
  1786. string text,
  1787. Rune hotKeySpecifier,
  1788. out int hotPos,
  1789. out Key hotKey,
  1790. bool firstUpperCase = false
  1791. )
  1792. {
  1793. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  1794. {
  1795. hotPos = -1;
  1796. hotKey = Key.Empty;
  1797. return false;
  1798. }
  1799. var curHotKey = (Rune)0;
  1800. int curHotPos = -1;
  1801. // Use first hot_key char passed into 'hotKey'.
  1802. // TODO: Ignore hot_key of two are provided
  1803. // TODO: Do not support non-alphanumeric chars that can't be typed
  1804. var i = 0;
  1805. foreach (Rune c in text.EnumerateRunes ())
  1806. {
  1807. if ((char)c.Value != 0xFFFD)
  1808. {
  1809. if (c == hotKeySpecifier)
  1810. {
  1811. curHotPos = i;
  1812. }
  1813. else if (curHotPos > -1)
  1814. {
  1815. curHotKey = c;
  1816. break;
  1817. }
  1818. }
  1819. i++;
  1820. }
  1821. // Legacy support - use first upper case char if the specifier was not found
  1822. if (curHotPos == -1 && firstUpperCase)
  1823. {
  1824. i = 0;
  1825. foreach (Rune c in text.EnumerateRunes ())
  1826. {
  1827. if ((char)c.Value != 0xFFFD)
  1828. {
  1829. if (Rune.IsUpper (c))
  1830. {
  1831. curHotKey = c;
  1832. curHotPos = i;
  1833. break;
  1834. }
  1835. }
  1836. i++;
  1837. }
  1838. }
  1839. if (curHotKey != (Rune)0 && curHotPos != -1)
  1840. {
  1841. hotPos = curHotPos;
  1842. var newHotKey = (KeyCode)curHotKey.Value;
  1843. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  1844. {
  1845. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  1846. {
  1847. newHotKey &= ~KeyCode.Space;
  1848. }
  1849. hotKey = newHotKey;
  1850. //hotKey.Scope = KeyBindingScope.HotKey;
  1851. return true;
  1852. }
  1853. }
  1854. hotPos = -1;
  1855. hotKey = KeyCode.Null;
  1856. return false;
  1857. }
  1858. /// <summary>
  1859. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  1860. /// hotkey.
  1861. /// </summary>
  1862. /// <param name="text">The text to tag the hotkey in.</param>
  1863. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1864. /// <returns>The text with the hotkey tagged.</returns>
  1865. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  1866. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  1867. {
  1868. // Set the high bit
  1869. List<Rune> runes = text.ToRuneList ();
  1870. if (Rune.IsLetterOrDigit (runes [hotPos]))
  1871. {
  1872. runes [hotPos] = new Rune ((uint)runes [hotPos].Value);
  1873. }
  1874. return StringExtensions.ToString (runes);
  1875. }
  1876. /// <summary>Removes the hotkey specifier from text.</summary>
  1877. /// <param name="text">The text to manipulate.</param>
  1878. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1879. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1880. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1881. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  1882. {
  1883. if (string.IsNullOrEmpty (text))
  1884. {
  1885. return text;
  1886. }
  1887. // Scan
  1888. var start = string.Empty;
  1889. var i = 0;
  1890. foreach (Rune c in text)
  1891. {
  1892. if (c == hotKeySpecifier && i == hotPos)
  1893. {
  1894. i++;
  1895. continue;
  1896. }
  1897. start += c;
  1898. i++;
  1899. }
  1900. return start;
  1901. }
  1902. #endregion // Static Members
  1903. }