TextFormatter.cs 80 KB

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