-
Notifications
You must be signed in to change notification settings - Fork 673
/
TextFormatter.cs
1333 lines (1234 loc) · 42.1 KB
/
TextFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NStack;
namespace Terminal.Gui {
/// <summary>
/// Text alignment enumeration, controls how text is displayed.
/// </summary>
public enum TextAlignment {
/// <summary>
/// Aligns the text to the left of the frame.
/// </summary>
Left,
/// <summary>
/// Aligns the text to the right side of the frame.
/// </summary>
Right,
/// <summary>
/// Centers the text in the frame.
/// </summary>
Centered,
/// <summary>
/// Shows the text as justified text in the frame.
/// </summary>
Justified
}
/// <summary>
/// Vertical text alignment enumeration, controls how text is displayed.
/// </summary>
public enum VerticalTextAlignment {
/// <summary>
/// Aligns the text to the top of the frame.
/// </summary>
Top,
/// <summary>
/// Aligns the text to the bottom of the frame.
/// </summary>
Bottom,
/// <summary>
/// Centers the text verticaly in the frame.
/// </summary>
Middle,
/// <summary>
/// Shows the text as justified text in the frame.
/// </summary>
Justified
}
/// TextDirection [H] = Horizontal [V] = Vertical
/// =============
/// LeftRight_TopBottom [H] Normal
/// TopBottom_LeftRight [V] Normal
///
/// RightLeft_TopBottom [H] Invert Text
/// TopBottom_RightLeft [V] Invert Lines
///
/// LeftRight_BottomTop [H] Invert Lines
/// BottomTop_LeftRight [V] Invert Text
///
/// RightLeft_BottomTop [H] Invert Text + Invert Lines
/// BottomTop_RightLeft [V] Invert Text + Invert Lines
///
/// <summary>
/// Text direction enumeration, controls how text is displayed.
/// </summary>
public enum TextDirection {
/// <summary>
/// Normal horizontal direction.
/// <code>HELLO<br/>WORLD</code>
/// </summary>
LeftRight_TopBottom,
/// <summary>
/// Normal vertical direction.
/// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
/// </summary>
TopBottom_LeftRight,
/// <summary>
/// This is a horizontal direction. <br/> RTL
/// <code>OLLEH<br/>DLROW</code>
/// </summary>
RightLeft_TopBottom,
/// <summary>
/// This is a vertical direction.
/// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
/// </summary>
TopBottom_RightLeft,
/// <summary>
/// This is a horizontal direction.
/// <code>WORLD<br/>HELLO</code>
/// </summary>
LeftRight_BottomTop,
/// <summary>
/// This is a vertical direction.
/// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
/// </summary>
BottomTop_LeftRight,
/// <summary>
/// This is a horizontal direction.
/// <code>DLROW<br/>OLLEH</code>
/// </summary>
RightLeft_BottomTop,
/// <summary>
/// This is a vertical direction.
/// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
/// </summary>
BottomTop_RightLeft
}
/// <summary>
/// Provides text formatting capabilities for console apps. Supports, hotkeys, horizontal alignment, multiple lines, and word-based line wrap.
/// </summary>
public class TextFormatter {
List<ustring> lines = new List<ustring> ();
ustring text;
TextAlignment textAlignment;
VerticalTextAlignment textVerticalAlignment;
TextDirection textDirection;
Attribute textColor = -1;
bool needsFormat;
Key hotKey;
Size size;
/// <summary>
/// Event invoked when the <see cref="HotKey"/> is changed.
/// </summary>
public event Action<Key> HotKeyChanged;
/// <summary>
/// The text to be displayed. This text is never modified.
/// </summary>
public virtual ustring Text {
get => text;
set {
text = value;
if (text != null && text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.ConsoleWidth)) {
// Provide a default size (width = length of longest line, height = 1)
// TODO: It might makes more sense for the default to be width = length of first line?
Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
}
NeedsFormat = true;
}
}
/// <summary>
/// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
/// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
/// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
/// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
/// </summary>
public bool AutoSize { get; set; }
/// <summary>
/// Gets or sets a flag that determines whether <see cref="Text"/> will have trailing spaces preserved
/// or not when <see cref="WordWrap"/> is enabled. If `true` any trailing spaces will be trimmed when
/// either the <see cref="Text"/> property is changed or when <see cref="WordWrap"/> is set to `true`.
/// The default is `false`.
/// </summary>
public bool PreserveTrailingSpaces { get; set; }
/// <summary>
/// Controls the horizontal text-alignment property.
/// </summary>
/// <value>The text alignment.</value>
public TextAlignment Alignment {
get => textAlignment;
set {
textAlignment = value;
NeedsFormat = true;
}
}
/// <summary>
/// Controls the vertical text-alignment property.
/// </summary>
/// <value>The text vertical alignment.</value>
public VerticalTextAlignment VerticalAlignment {
get => textVerticalAlignment;
set {
textVerticalAlignment = value;
NeedsFormat = true;
}
}
/// <summary>
/// Controls the text-direction property.
/// </summary>
/// <value>The text vertical alignment.</value>
public TextDirection Direction {
get => textDirection;
set {
textDirection = value;
NeedsFormat = true;
}
}
/// <summary>
/// Check if it is a horizontal direction
/// </summary>
public static bool IsHorizontalDirection (TextDirection textDirection)
{
switch (textDirection) {
case TextDirection.LeftRight_TopBottom:
case TextDirection.LeftRight_BottomTop:
case TextDirection.RightLeft_TopBottom:
case TextDirection.RightLeft_BottomTop:
return true;
default:
return false;
}
}
/// <summary>
/// Check if it is a vertical direction
/// </summary>
public static bool IsVerticalDirection (TextDirection textDirection)
{
switch (textDirection) {
case TextDirection.TopBottom_LeftRight:
case TextDirection.TopBottom_RightLeft:
case TextDirection.BottomTop_LeftRight:
case TextDirection.BottomTop_RightLeft:
return true;
default:
return false;
}
}
/// <summary>
/// Check if it is Left to Right direction
/// </summary>
public static bool IsLeftToRight (TextDirection textDirection)
{
switch (textDirection) {
case TextDirection.LeftRight_TopBottom:
case TextDirection.LeftRight_BottomTop:
return true;
default:
return false;
}
}
/// <summary>
/// Check if it is Top to Bottom direction
/// </summary>
public static bool IsTopToBottom (TextDirection textDirection)
{
switch (textDirection) {
case TextDirection.TopBottom_LeftRight:
case TextDirection.TopBottom_RightLeft:
return true;
default:
return false;
}
}
/// <summary>
/// Gets or sets the size of the area the text will be constrained to when formatted.
/// </summary>
public Size Size {
get => size;
set {
size = value;
NeedsFormat = true;
}
}
/// <summary>
/// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
/// </summary>
public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
/// <summary>
/// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
/// </summary>
public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
/// <summary>
/// Gets the hotkey. Will be an upper case letter or digit.
/// </summary>
public Key HotKey {
get => hotKey;
internal set {
if (hotKey != value) {
var oldKey = hotKey;
hotKey = value;
HotKeyChanged?.Invoke (oldKey);
}
}
}
/// <summary>
/// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
/// </summary>
public int CursorPosition { get; set; }
/// <summary>
/// Gets the formatted lines.
/// </summary>
/// <remarks>
/// <para>
/// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
/// <see cref="Format(ustring, int, bool, bool, bool, int, TextDirection)"/> will be called internally.
/// </para>
/// </remarks>
public List<ustring> Lines {
get {
// With this check, we protect against subclasses with overrides of Text
if (ustring.IsNullOrEmpty (Text) || Size.IsEmpty) {
lines = new List<ustring> {
ustring.Empty
};
NeedsFormat = false;
return lines;
}
if (NeedsFormat) {
var shown_text = text;
if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out Key newHotKey)) {
HotKey = newHotKey;
shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
}
if (IsVerticalDirection (textDirection)) {
var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1);
lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth,
PreserveTrailingSpaces, 0, textDirection);
if (!AutoSize) {
colsWidth = GetMaxColsForWidth (lines, Size.Width);
if (lines.Count > colsWidth) {
lines.RemoveRange (colsWidth, lines.Count - colsWidth);
}
}
} else {
lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1,
PreserveTrailingSpaces, 0, textDirection);
if (!AutoSize && lines.Count > Size.Height) {
lines.RemoveRange (Size.Height, lines.Count - Size.Height);
}
}
NeedsFormat = false;
}
return lines;
}
}
/// <summary>
/// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect, bool)"/> is called.
/// If it is <c>false</c> when Draw is called, the Draw call will be faster.
/// </summary>
/// <remarks>
/// <para>
/// This is set to true when the properties of <see cref="TextFormatter"/> are set.
/// </para>
/// </remarks>
public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
static ustring StripCRLF (ustring str, bool keepNewLine = false)
{
var runes = str.ToRuneList ();
for (int i = 0; i < runes.Count; i++) {
switch (runes [i]) {
case '\n':
if (!keepNewLine) {
runes.RemoveAt (i);
}
break;
case '\r':
if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
runes.RemoveAt (i);
if (!keepNewLine) {
runes.RemoveAt (i);
}
i++;
} else {
if (!keepNewLine) {
runes.RemoveAt (i);
}
}
break;
}
}
return ustring.Make (runes);
}
static ustring ReplaceCRLFWithSpace (ustring str)
{
var runes = str.ToRuneList ();
for (int i = 0; i < runes.Count; i++) {
switch (runes [i]) {
case '\n':
runes [i] = (Rune)' ';
break;
case '\r':
if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
runes [i] = (Rune)' ';
runes.RemoveAt (i + 1);
i++;
} else {
runes [i] = (Rune)' ';
}
break;
}
}
return ustring.Make (runes);
}
/// <summary>
/// Splits all newlines in the <paramref name="text"/> into a list
/// and supports both CRLF and LF, preserving the ending newline.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>A list of text without the newline characters.</returns>
public static List<ustring> SplitNewLine (ustring text)
{
var runes = text.ToRuneList ();
var lines = new List<ustring> ();
var start = 0;
var end = 0;
for (int i = 0; i < runes.Count; i++) {
end = i;
switch (runes [i]) {
case '\n':
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
i++;
start = i;
break;
case '\r':
if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
i += 2;
start = i;
} else {
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
i++;
start = i;
}
break;
}
}
if (runes.Count > 0 && lines.Count == 0) {
lines.Add (ustring.Make (runes));
} else if (runes.Count > 0 && start < runes.Count) {
lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
} else {
lines.Add (ustring.Make (""));
}
return lines;
}
/// <summary>
/// Adds trailing whitespace or truncates <paramref name="text"/>
/// so that it fits exactly <paramref name="width"/> console units.
/// Note that some unicode characters take 2+ columns
/// </summary>
/// <param name="text"></param>
/// <param name="width"></param>
/// <returns></returns>
public static string ClipOrPad (string text, int width)
{
if (string.IsNullOrEmpty (text))
return text;
// if value is not wide enough
if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
// pad it out with spaces to the given alignment
int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
return text + new string (' ', toPad);
}
// value is too wide
return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
}
/// <summary>
/// Formats the provided text to fit within the width provided using word wrapping.
/// </summary>
/// <param name="text">The text to word wrap</param>
/// <param name="width">The width to contain the text to</param>
/// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
/// If <c>false</c>, the trailing spaces will be trimmed.</param>
/// <param name="tabWidth">The tab width.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>Returns a list of word wrapped lines.</returns>
/// <remarks>
/// <para>
/// This method does not do any justification.
/// </para>
/// <para>
/// This method strips Newline ('\n' and '\r\n') sequences before processing.
/// </para>
/// </remarks>
public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
if (width < 0) {
throw new ArgumentOutOfRangeException ("Width cannot be negative.");
}
int start = 0, end;
var lines = new List<ustring> ();
if (ustring.IsNullOrEmpty (text)) {
return lines;
}
var runes = StripCRLF (text).ToRuneList ();
if (!preserveTrailingSpaces) {
if (IsHorizontalDirection (textDirection)) {
while ((end = start + Math.Max (GetMaxLengthForWidth (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
while (runes [end] != ' ' && end > start)
end--;
if (end == start)
end = start + GetMaxLengthForWidth (runes.GetRange (end, runes.Count - end), width);
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
start = end;
if (runes [end] == ' ') {
start++;
}
}
} else {
while ((end = start + width) < runes.Count) {
while (runes [end] != ' ' && end > start)
end--;
if (end == start)
end = start + width;
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
start = end;
if (runes [end] == ' ') {
start++;
}
}
}
} else {
while ((end = start) < runes.Count) {
end = GetNextWhiteSpace (start, width, out bool incomplete);
if (end == 0 && incomplete) {
start = text.RuneCount;
break;
}
lines.Add (ustring.Make (runes.GetRange (start, end - start)));
start = end;
if (incomplete) {
start = text.RuneCount;
break;
}
}
}
int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
{
var lastFrom = from;
var to = from;
var length = cLength;
incomplete = false;
while (length < cWidth && to < runes.Count) {
var rune = runes [to];
if (IsHorizontalDirection (textDirection)) {
length += Rune.ColumnWidth (rune);
} else {
length++;
}
if (length > cWidth) {
if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
incomplete = true;
}
return to;
}
if (rune == ' ') {
if (length == cWidth) {
return to + 1;
} else if (length > cWidth) {
return to;
} else {
return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
}
} else if (rune == '\t') {
length += tabWidth + 1;
if (length == tabWidth && tabWidth > cWidth) {
return to + 1;
} else if (length > cWidth && tabWidth > cWidth) {
return to;
} else {
return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
}
}
to++;
}
if (cLength > 0 && to < runes.Count && runes [to] != ' ' && runes [to] != '\t') {
return from;
} else if (cLength > 0 && to < runes.Count && (runes [to] == ' ' || runes [to] == '\t')) {
return lastFrom;
} else {
return to;
}
}
if (start < text.RuneCount) {
lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
}
return lines;
}
/// <summary>
/// Justifies text within a specified width.
/// </summary>
/// <param name="text">The text to justify.</param>
/// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
/// <param name="talign">Alignment.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>Justified and clipped text.</returns>
public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
}
/// <summary>
/// Justifies text within a specified width.
/// </summary>
/// <param name="text">The text to justify.</param>
/// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
/// <param name="justify">Justify.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>Justified and clipped text.</returns>
public static ustring ClipAndJustify (ustring text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
if (width < 0) {
throw new ArgumentOutOfRangeException ("Width cannot be negative.");
}
if (ustring.IsNullOrEmpty (text)) {
return text;
}
var runes = text.ToRuneList ();
int slen = runes.Count;
if (slen > width) {
if (IsHorizontalDirection (textDirection)) {
return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
} else {
return ustring.Make (runes.GetRange (0, width));
}
} else {
if (justify) {
return Justify (text, width, ' ', textDirection);
} else if (IsHorizontalDirection (textDirection) && GetTextWidth (text) > width) {
return ustring.Make (runes.GetRange (0, GetMaxLengthForWidth (text, width)));
}
return text;
}
}
/// <summary>
/// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
/// make the text just fit <c>width</c>. Spaces will not be added to the ends.
/// </summary>
/// <param name="text"></param>
/// <param name="width"></param>
/// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>The justified text.</returns>
public static ustring Justify (ustring text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
if (width < 0) {
throw new ArgumentOutOfRangeException ("Width cannot be negative.");
}
if (ustring.IsNullOrEmpty (text)) {
return text;
}
var words = text.Split (ustring.Make (' '));
int textCount;
if (IsHorizontalDirection (textDirection)) {
textCount = words.Sum (arg => GetTextWidth (arg));
} else {
textCount = words.Sum (arg => arg.RuneCount);
}
var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
var extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
var s = new System.Text.StringBuilder ();
for (int w = 0; w < words.Length; w++) {
var x = words [w];
s.Append (x);
if (w + 1 < words.Length)
for (int i = 0; i < spaces; i++)
s.Append (spaceChar);
if (extras > 0) {
for (int i = 0; i < 1; i++)
s.Append (spaceChar);
extras--;
}
if (w + 1 == words.Length - 1) {
for (int i = 0; i < extras; i++)
s.Append (spaceChar);
}
}
return ustring.Make (s.ToString ());
}
static char [] whitespace = new char [] { ' ', '\t' };
private int hotKeyPos = -1;
/// <summary>
/// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
/// </summary>
/// <param name="text"></param>
/// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
/// <param name="talign">Specifies how the text will be aligned horizontally.</param>
/// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
/// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
/// <param name="tabWidth">The tab width.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>A list of word wrapped lines.</returns>
/// <remarks>
/// <para>
/// An empty <c>text</c> string will result in one empty line.
/// </para>
/// <para>
/// If <c>width</c> is 0, a single, empty line will be returned.
/// </para>
/// <para>
/// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
/// </para>
/// </remarks>
public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
}
/// <summary>
/// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
/// </summary>
/// <param name="text"></param>
/// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
/// <param name="justify">Specifies whether the text should be justified.</param>
/// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
/// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
/// <param name="tabWidth">The tab width.</param>
/// <param name="textDirection">The text direction.</param>
/// <returns>A list of word wrapped lines.</returns>
/// <remarks>
/// <para>
/// An empty <c>text</c> string will result in one empty line.
/// </para>
/// <para>
/// If <c>width</c> is 0, a single, empty line will be returned.
/// </para>
/// <para>
/// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
/// </para>
/// </remarks>
public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
{
if (width < 0) {
throw new ArgumentOutOfRangeException ("width cannot be negative");
}
List<ustring> lineResult = new List<ustring> ();
if (ustring.IsNullOrEmpty (text) || width == 0) {
lineResult.Add (ustring.Empty);
return lineResult;
}
if (wordWrap == false) {
text = ReplaceCRLFWithSpace (text);
lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
return lineResult;
}
var runes = StripCRLF (text, true).ToRuneList ();
int runeCount = runes.Count;
int lp = 0;
for (int i = 0; i < runeCount; i++) {
Rune c = runes [i];
if (c == '\n') {
var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
foreach (var line in wrappedLines) {
lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
}
if (wrappedLines.Count == 0) {
lineResult.Add (ustring.Empty);
}
lp = i + 1;
}
}
foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
}
return lineResult;
}
/// <summary>
/// Computes the number of lines needed to render the specified text given the width.
/// </summary>
/// <returns>Number of lines.</returns>
/// <param name="text">Text, may contain newlines.</param>
/// <param name="width">The minimum width for the text.</param>
public static int MaxLines (ustring text, int width)
{
var result = TextFormatter.Format (text, width, false, true);
return result.Count;
}
/// <summary>
/// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
/// </summary>
/// <returns>Max width of lines.</returns>
/// <param name="text">Text, may contain newlines.</param>
/// <param name="width">The minimum width for the text.</param>
public static int MaxWidth (ustring text, int width)
{
var result = TextFormatter.Format (text, width, false, true);
var max = 0;
result.ForEach (s => {
var m = 0;
s.ToRuneList ().ForEach (r => m += Math.Max (Rune.ColumnWidth (r), 1));
if (m > max) {
max = m;
}
});
return max;
}
/// <summary>
/// Determines the line with the highest width in the
/// <paramref name="text"/> if it contains newlines.
/// </summary>
/// <param name="text">Text, may contain newlines.</param>
/// <returns>The highest line width.</returns>
public static int MaxWidthLine (ustring text)
{
var result = TextFormatter.SplitNewLine (text);
return result.Max (x => x.ConsoleWidth);
}
/// <summary>
/// Gets the total width of the passed text.
/// </summary>
/// <param name="text"></param>
/// <returns>The text width.</returns>
public static int GetTextWidth (ustring text)
{
return text.ToRuneList ().Sum (r => Math.Max (Rune.ColumnWidth (r), 1));
}
/// <summary>
/// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
/// and the <paramref name="length"/>.
/// </summary>
/// <param name="lines">The lines.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns>The maximum characters width.</returns>
public static int GetSumMaxCharWidth (List<ustring> lines, int startIndex = -1, int length = -1)
{
var max = 0;
for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
var runes = lines [i];
if (runes.Length > 0)
max += runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1));
}
return max;
}
/// <summary>
/// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
/// and the <paramref name="length"/>.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns>The maximum characters width.</returns>
public static int GetSumMaxCharWidth (ustring text, int startIndex = -1, int length = -1)
{
var max = 0;
var runes = text.ToRunes ();
for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
max += Math.Max (Rune.ColumnWidth (runes [i]), 1);
}
return max;
}
/// <summary>
/// Gets the index position from the text based on the <paramref name="width"/>.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="width">The width.</param>
/// <returns>The index of the text that fit the width.</returns>
public static int GetMaxLengthForWidth (ustring text, int width)
{
var runes = text.ToRuneList ();
var runesLength = 0;
var runeIdx = 0;
for (; runeIdx < runes.Count; runeIdx++) {
var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
if (runesLength + runeWidth > width) {
break;
}
runesLength += runeWidth;
}
return runeIdx;
}
/// <summary>
/// Gets the index position from the list based on the <paramref name="width"/>.
/// </summary>
/// <param name="runes">The runes.</param>
/// <param name="width">The width.</param>
/// <returns>The index of the list that fit the width.</returns>
public static int GetMaxLengthForWidth (List<Rune> runes, int width)
{
var runesLength = 0;
var runeIdx = 0;
for (; runeIdx < runes.Count; runeIdx++) {
var runeWidth = Math.Max (Rune.ColumnWidth (runes [runeIdx]), 1);
if (runesLength + runeWidth > width) {
break;
}
runesLength += runeWidth;
}
return runeIdx;
}
/// <summary>
/// Gets the index position from the list based on the <paramref name="width"/>.
/// </summary>
/// <param name="lines">The lines.</param>
/// <param name="width">The width.</param>
/// <returns>The index of the list that fit the width.</returns>
public static int GetMaxColsForWidth (List<ustring> lines, int width)
{
var runesLength = 0;
var lineIdx = 0;
for (; lineIdx < lines.Count; lineIdx++) {
var runes = lines [lineIdx].ToRuneList ();
var maxRruneWidth = runes.Count > 0
? runes.Max (r => Math.Max (Rune.ColumnWidth (r), 1)) : 1;
if (runesLength + maxRruneWidth > width) {
break;
}
runesLength += maxRruneWidth;
}
return lineIdx;
}
/// <summary>
/// Calculates the rectangle required to hold text, assuming no word wrapping.
/// </summary>
/// <param name="x">The x location of the rectangle</param>
/// <param name="y">The y location of the rectangle</param>
/// <param name="text">The text to measure</param>
/// <param name="direction">The text direction.</param>
/// <returns></returns>
public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
{
if (ustring.IsNullOrEmpty (text)) {
return new Rect (new Point (x, y), Size.Empty);
}
int w, h;
if (IsHorizontalDirection (direction)) {
int mw = 0;
int ml = 1;
int cols = 0;
foreach (var rune in text) {
if (rune == '\n') {
ml++;
if (cols > mw) {
mw = cols;
}
cols = 0;
} else if (rune != '\r') {
cols++;
var rw = Rune.ColumnWidth (rune);
if (rw > 0) {
rw--;
}
cols += rw;
}
}
if (cols > mw) {
mw = cols;
}