TextFormatter.cs 77 KB

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