TextFormatter.cs 78 KB

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