TextFormatter.cs 80 KB

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