TextFormatter.cs 82 KB

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