TextFormatter.cs 77 KB

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