forked from AndrewBarker12345/3DAudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextUtils.cpp
6274 lines (5989 loc) · 249 KB
/
TextUtils.cpp
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
//
// TextUtils.cpp
// ThreeDAudio
//
// Created by Andrew Barker on 3/2/16.
//
//
#include "TextUtils.h"
#include <iostream>
#include <fstream>
#include <numeric>
void findAndReplace(std::string& str,
const std::string& find,
const std::string& replace) noexcept
{
std::string::size_type n;
while ((n = str.find(find)) != std::string::npos) {
str.replace(n, find.length(), replace);
}
}
std::string getLeadingWhitespace(const std::string& str) noexcept
{
if (str.length() > 0 && str[0] == ' ')
return str.substr(0, std::distance(std::begin(str),
std::find_if_not(std::begin(str) + 1, std::end(str),
[](const auto& c){return c == ' ';})));
return std::string();
}
std::string getTrailingWhitespace(const std::string& str) noexcept
{
auto copy = str;
std::reverse(std::begin(copy), std::end(copy));
return getLeadingWhitespace(copy);
}
int removeFirstWhitespaceIfLessThan(std::string& str,
const int spacesCount)
{
int numSpacesRemoved;
const auto firstNonWhitespace = std::find_if(std::begin(str), std::end(str), [](const auto& c){return c != ' ';});
if ((numSpacesRemoved = std::distance(std::begin(str), firstNonWhitespace)) < spacesCount)
str.erase(std::begin(str), firstNonWhitespace);
else
numSpacesRemoved = 0;
return numSpacesRemoved;
}
int removeLastWhitespaceIfLessThan(std::string& str,
const int spacesCount)
{
int numSpacesRemoved;
std::reverse(std::begin(str), std::end(str));
numSpacesRemoved = removeFirstWhitespaceIfLessThan(str, spacesCount);
std::reverse(std::begin(str), std::end(str));
return numSpacesRemoved;
}
void removeFirstWhitespace(std::string& str) noexcept
{
str.erase(std::begin(str), std::find_if(std::begin(str), std::end(str), [](const auto& c){return c != ' ';}));
}
void removeLastWhitespace(std::string& str) noexcept
{
std::reverse(std::begin(str), std::end(str));
removeFirstWhitespace(str);
std::reverse(std::begin(str), std::end(str));
}
std::vector<std::string> parseStringIntoWords(const std::string& text)
{
std::vector<std::string> words;
int begin = 0;
for (int i = 0; i < text.size(); ++i) {
if (text[i] == '\n' || text[i] == '\r') { // newline
if (i > begin) // add any non-whitespace word before the newline
words.emplace_back(text.substr(begin, i-begin));
// else if (words.size() > 0 && words.back().length() > 0 && words.back()[0] == ' ')
// words.pop_back(); // remove any whitespace before the newline
words.emplace_back("\n"); // add the newline as a word
begin = i+1;
} else if (text[i] == ' ') { // if we found the ending of a non-whitespace word
if (i > begin) // don't skip loading first word if it is white space
words.emplace_back(text.substr(begin, i-begin));
for (int j = i+1; j <= text.size(); ++j) { // load white space words
if (j < text.size() && text[j] != ' ') {
words.emplace_back(text.substr(i, j-i));
begin = j;
i = j-1;
j = text.size(); // exit for j loop
} else if (j == text.size()) { // load last word if it is white space
words.emplace_back(text.substr(i, text.size()-i));
i = j-1;
}
}
} else if (i == text.size()-1) { // load last non-whitespace word
words.emplace_back(text.substr(begin, text.size()-begin));
}
}
return words;
}
void glColour(Colour color)
{
glColor4f(color.getFloatRed(), color.getFloatGreen(), color.getFloatBlue(), color.getFloatAlpha());
currentGLColor = color;
}
MouseDependentAnimation::MouseDependentAnimation(const float durationInSeconds) noexcept
: Animation(durationInSeconds)
{
}
//Box::Box(const Point<float>& pt,
// const float radius) noexcept
// : top (pt.y + radius),
// bottom (pt.y - radius),
// left (pt.x - radius),
// right (pt.x + radius)
//{
//}
//
//bool Box::operator==(const Box& box) const noexcept
//{
// return top == box.top && bottom == box.bottom && left == box.left && right == box.right;
//}
//
//bool Box::operator!=(const Box& box) const noexcept
//{
// return top != box.top || bottom != box.bottom || left != box.left || right != box.right;
//}
//
//void Box::draw() const
//{
// glBegin(GL_LINE_LOOP);
// glVertex2f(left, top);
// glVertex2f(right, top);
// glVertex2f(right, bottom);
// glVertex2f(left, bottom);
// glEnd();
//}
//
//void Box::drawFill() const
//{
// glBegin(GL_QUADS);
// glVertex2f(left, top);
// glVertex2f(right, top);
// glVertex2f(right, bottom);
// glVertex2f(left, bottom);
// glEnd();
//}
//
//float Box::getWidth() const noexcept
//{
// return right - left;
//}
//
//float Box::getHeight() const noexcept
//{
// return top - bottom;
//}
//
//std::vector<Point<float>> Box::getBoundaryPoints() const noexcept
//{
// return {{left, top}, {right, top}, {right, bottom}, {left, bottom}};
//}
//
//bool Box::contains(const Point<float>& pt) const noexcept
//{
// return left <= pt.x && pt.x <= right && bottom <= pt.y && pt.y <= top;
//}
//
//bool Box::overlaps(const Box& box) const noexcept
//{
// return ! (bottom > box.top || top < box.bottom || left > box.right || right < box.left);
//}
//
//void Box::crop(const Box& box) noexcept
//{
// if (top > box.top)
// top = box.top;
// if (bottom < box.bottom)
// bottom = box.bottom;
// if (left < box.left)
// left = box.left;
// if (right > box.right)
// right = box.right;
//}
//
//Box combined(const Box& b1, const Box& b2) noexcept
//{
// return { std::max(b1.top, b2.top), std::min(b1.bottom, b2.bottom),
// std::min(b1.left, b2.left), std::max(b1.right, b2.right) };
//}
//
//Box getScaled(const Box& b, const float hScale, const float vScale) noexcept
//{
// const float dWidth = b.getWidth() * 0.5 * (1.0 - hScale);
// const float dHeight = b.getHeight() * 0.5 * (1.0 - vScale);
// const float top = b.top - dHeight;
// const float bottom = b.bottom + dHeight;
// const float left = b.left + dWidth;
// const float right = b.right - dWidth;
// return {top, bottom, left, right};
//}
int normalizedToPixels(const float normalizedLength,
const int windowLength) noexcept
{
return std::round(windowLength * normalizedLength * 0.5f);
}
Point<int> normalizedToPixels(const Point<float>& normalizedPoint,
const int windowWidth,
const int windowHeight) noexcept
{
return {static_cast<int>(std::round( (normalizedPoint.getX() + 1) * 0.5f * windowWidth)),
static_cast<int>(std::round((1 - ((normalizedPoint.getY() + 1) * 0.5f)) * windowHeight))};
}
Rectangle<int> normalizedToPixels(const Box& normalizedRect,
const int windowWidth,
const int windowHeight) noexcept
{
return {normalizedToPixels({normalizedRect.getLeft(), normalizedRect.getTop()}, windowWidth, windowHeight),
normalizedToPixels({normalizedRect.getRight(), normalizedRect.getBottom()}, windowWidth, windowHeight)};
}
float pixelsToNormalized(const float lengthInPixels,
const int windowLengthPixels) noexcept
{
return 2.0f * lengthInPixels / windowLengthPixels;
}
Point<float> pixelsToNormalized(const Point<int>& ptInPixels,
const int windowWidth,
const int windowHeight) noexcept
{
return {pixelsToNormalized(ptInPixels.x, windowWidth) - 1,
1 - pixelsToNormalized(ptInPixels.y, windowHeight)};
}
float normalizedXYConvert(const float fromLengthNormalized,
const float fromWindowLengthInPixels,
const float toWindowLengthInPixels) noexcept
{
const auto px = normalizedToPixels(fromLengthNormalized, fromWindowLengthInPixels);
return pixelsToNormalized(px, toWindowLengthInPixels);
}
//void OpenGLWindow::checkResized(const int w,
// const int h) noexcept
//{
// if (w != width || h != height) {
// resized = true;
// width = w;
// height = h;
// }
//}
//
//void OpenGLWindow::saveResized() noexcept
//{
// resized = false;
//}
Texture::Texture(const Box& boundary) noexcept
: boundary(boundary), redrawToTexture(true)
{
}
Texture::Texture(const Texture& copyFrom) noexcept
: boundary(copyFrom.boundary), redrawToTexture(true)
{
}
Texture& Texture::operator=(const Texture& copyFrom) noexcept
{
if (©From != this) {
boundary = copyFrom.boundary;
redrawToTexture = true;
}
return *this;
}
void TextLook::draw(const std::string& text,
Texture& texture,
OpenGLWindow& window,
const float otherFontSize,
const float otherHorizontalPad,
std::vector<std::string>* const getLines,
Font* const getFont,
const int numSpacesForTab,
const float yScrollOffsetPercent,
const float xScrollOffsetPercent,
float* const longestLineWidth) const
{
if (window.resized || texture.redrawToTexture) {
const float whichFontSize = relativeScale * (otherFontSize > 0 ? otherFontSize : fontSize);
const float whichHorizontalPad = otherHorizontalPad > 0 ? otherHorizontalPad : horizontalPad;
const Box boundary = texture.boundary.scaled(relativeScale, relativeScale);
const Box paddedBoundary = boundary.scaled(whichHorizontalPad, verticalPad);
const int imageWidth = normalizedToPixels(boundary.width(), window.width);
const int imageHeight = normalizedToPixels(boundary.height(), window.height);
const int paddedWidth = normalizedToPixels(paddedBoundary.width(), window.width);
const int paddedHeight = normalizedToPixels(paddedBoundary.height(), window.height);
Image image (Image::ARGB, std::max(imageWidth, 1), std::max(imageHeight, 1), true); // avoid crash if image area happens to be 0 for some reason
Graphics g (image);
g.setColour(color);
// const auto linesAndFont = getLinesAndFont(text, texture.boundary, window.width, window.height);
// const auto lines = linesAndFont.first;
// const auto font = linesAndFont.second;
if (multiLine) {
Font font = getFontWithSize(whichFontSize);
std::vector<std::string> lines;
if (whichFontSize > 0) {
font.setHeight(whichFontSize);
lines = getLinesWithFontSize(parseStringIntoWords(text), wrap ? paddedWidth : -1, whichFontSize);
} else {
const auto linesAndMaxFontSize = getLinesAndMaxFontSize(parseStringIntoWords(text), paddedWidth, paddedHeight);
lines = linesAndMaxFontSize.first;
font.setHeight(linesAndMaxFontSize.second);
}
if (getLines) *getLines = lines;
if (getFont) *getFont = font;
for (auto& l : lines) // remove any newline characters from end of lines
findAndReplace(l, "\n", "");
// if left justified, remove all leading whitespace less than a tab
if (just.testFlags(Justification::left))
for (auto& l : lines)
removeFirstWhitespaceIfLessThan(l, numSpacesForTab);
// if right justified, remove all trailing whitespace less than a tab
else if (just.testFlags(Justification::right))
for (auto& l : lines)
removeLastWhitespaceIfLessThan(l, numSpacesForTab);
float longestLineWidthInPixels = 0;
if (longestLineWidth) {
for (const auto& l : lines)
if (longestLineWidthInPixels < font.getStringWidthFloat(l))
longestLineWidthInPixels = font.getStringWidthFloat(l);
*longestLineWidth = pixelsToNormalized(longestLineWidthInPixels, window.width);
}
g.setFont(font);
// the linePad is only relevant when we have two or more lines
const float whichLinePad = lines.size() > 1 ? linePad : 1;
const float totalTextHeightInPixels = std::max((int)lines.size(), 1)
* font.getHeight() / whichLinePad
- (1 - whichLinePad) * (lines.size() > 1 ? font.getHeight() / whichLinePad : 0);
// vertical justification needs to take into account all lines, default is centered
float vertJustOffset = 0.5f * (paddedHeight - totalTextHeightInPixels);
if (just.getOnlyVerticalFlags() == Justification::top)
vertJustOffset = 0.0f;
else if (just.getOnlyVerticalFlags() == Justification::bottom)
vertJustOffset *= 2.0f;
const float xOffsetBase = 0.5f * (imageWidth - paddedWidth) + horizontalOffset * font.getHeight()
- xScrollOffsetPercent * (longestLineWidthInPixels - paddedWidth);
// no vertical justification if scrolling is enabled
float yOffset = 0.5f * (imageHeight - paddedHeight)
+ (yScrollOffsetPercent >= 0 ? -yScrollOffsetPercent * (totalTextHeightInPixels - paddedHeight) : vertJustOffset);
for (const auto& line : lines) {
// if horizontally centered we need to handle leading/trailing whitespace spacing cuz juce's drawText() below centers the text as if there were equal amounts leading and trailing whitespace
float xOffsetAdjust = 0;
if (just.testFlags(Justification::horizontallyCentred))
xOffsetAdjust = std::round(0.5f * (font.getStringWidthFloat(getLeadingWhitespace(line))
- font.getStringWidthFloat(getTrailingWhitespace(line))));
g.drawText(line, std::round(xOffsetBase + xOffsetAdjust), std::round(yOffset), std::max(paddedWidth, (int)longestLineWidthInPixels), font.getHeight(), just, false);
yOffset += font.getHeight() / whichLinePad;
}
} else { // single-line text
Font font = getFontWithSize(paddedHeight);
float longestLineWidthInPixels = 0;
if (whichFontSize > 0) {
font.setHeight(whichFontSize);
longestLineWidthInPixels = font.getStringWidthFloat(text);
} else {
const float stringWidth = font.getStringWidthFloat(text);
const float scale = std::min(paddedWidth / stringWidth, 1.0f);
font.setHeight(paddedHeight * scale);
longestLineWidthInPixels = stringWidth * scale;
}
if (getLines) *getLines = {text};
if (getFont) *getFont = font;
if (longestLineWidth) *longestLineWidth = pixelsToNormalized(longestLineWidthInPixels, window.width);
g.setFont(font);
float xOffset = std::round(0.5f * (imageWidth - paddedWidth) + horizontalOffset * font.getHeight())
- xScrollOffsetPercent * (longestLineWidthInPixels - paddedWidth);
// if horizontally centered we need to handle leading/trailing whitespace spacing cuz juce's drawText() below centers the text as if there were equal amounts leading and trailing whitespace
if (just.testFlags(Justification::horizontallyCentred))
xOffset += std::round(0.5f * (font.getStringWidthFloat(getLeadingWhitespace(text))
- font.getStringWidthFloat(getTrailingWhitespace(text))));
const int yOffset = std::round(0.5f * (imageHeight - paddedHeight)
+ (yScrollOffsetPercent >= 0 ? -yScrollOffsetPercent * (font.getHeight() - paddedHeight) : 0));
g.drawText(text, std::round(xOffset), yOffset, std::max(paddedWidth, (int)longestLineWidthInPixels), paddedHeight, just, false);
}
for (const auto& e : effects)
e.apply(image, g, 1, 1);
const Point<int> textureTopLeft = normalizedToPixels({boundary.getLeft(), boundary.getTop()},
window.width, window.height);
texture.texture.release(); // make sure to free any previous texture memory
texture.texture.loadImage(image);
texture.clip = {textureTopLeft, {textureTopLeft.getX() + image.getWidth(),
textureTopLeft.getY() + image.getHeight()}};
texture.pos = {textureTopLeft, {textureTopLeft.getX() + texture.texture.getWidth(),
textureTopLeft.getY() + texture.texture.getHeight()}};
texture.redrawToTexture = false;
}
texture.texture.bind();
window.context->copyTexture(texture.clip, texture.pos, window.width, window.height, false);
texture.texture.unbind();
// need to reactivate alpha color stuff after drawing a texture for some reason
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // this does the trick
// glEnable(GL_BLEND); // ... but these might be necessary also
// glClearColor(0.0,0.0,0.0,0.0);
}
Font TextLook::getFont(const std::string& text,
const Box& boundary,
const int windowWidth,
const int windowHeight,
const float otherHorizontalPad) const
{
if (fontSize < 0) {
const float whichHorizontalPad = otherHorizontalPad > 0 ? otherHorizontalPad : horizontalPad;
const float w = normalizedToPixels(boundary.width() * relativeScale * whichHorizontalPad, windowWidth);
const float h = normalizedToPixels(boundary.height() * relativeScale * verticalPad, windowHeight);
const Font font = getFontWithSize(h);
if (boundary.width() == std::numeric_limits<float>::infinity())
return font;
else if (multiLine)
return getLinesAndMaxFontSize(parseStringIntoWords(text), w, h).second;
else
return getFontWithSize(h * std::min(w / font.getStringWidthFloat(text), 1.0f));
}
return getFontWithSize(fontSize * relativeScale);
}
std::pair<std::vector<std::string>, float>
TextLook::getLinesAndMaxFontSize(const std::vector<std::string>& words,
const float boxWidth,
const float boxHeight) const
{
std::vector<std::string> lines;
const Font font = getFontWithSize(boxHeight);
// compute a first order approx of the maximum text size
float totalLength = 0;
std::vector<float> wordLengths (words.size());
for (int i = 0; i < words.size(); ++i) {
wordLengths[i] = font.getStringWidthFloat(words[i]);
totalLength += wordLengths[i];
}
if (totalLength == 0) // if the text passed in is empty, we are done
return {lines, boxHeight};
const float initArea = totalLength / linePad;
float textScale = std::min(1.0f, std::sqrt(boxWidth / initArea));
TRY_AGAIN: // scale back further still if the text cannot be contained in the specified box height-wise
lines.clear();
const int numLines = linePad / textScale;
float textLength = 0;
int lineCount = 1;
for (int i = 0; i < words.size(); ++i) {
textLength += /*font.getStringWidthFloat(words[i])*/ wordLengths[i] * textScale; // WOW!!! huge performance boost!
if (textLength > boxWidth || words[i] == "\n") { // if we run over the bounday's width or hit a newline character, start a new line
if (words[i] == "\n") { // add newline word to end of line
while (lineCount-1 >= lines.size()) // prevent array out of bounds crashing
lines.emplace_back("");
lines[lineCount-1] += words[i];
}
if (++lineCount > numLines) { // micro-adjust scale until text fits height-wise
textScale *= 0.9999f;
lines.clear();
goto TRY_AGAIN;
}
textLength = 0;
if (words[i] != "\n") // resume with last non-newline word that didn't fit onto the previous line
--i;
} else {
while (lineCount-1 >= lines.size()) // prevent array out of bounds crashing
lines.emplace_back("");
lines[lineCount-1] += words[i];
}
}
if (lines.size() > 0 && lines.back().size() > 0 && lines.back().back() == '\n') // if the last line's last character is a newline, tag on an empty line
lines.emplace_back("");
return {lines, boxHeight * textScale};
}
std::vector<std::string> TextLook::getLinesWithFontSize(const std::vector<std::string>& words,
const float boxWidth,
const float fontSize) const
{
std::vector<std::string> lines;
const Font font = getFontWithSize(fontSize);
float textLength = 0;
int lineCount = 1;
int numWordsOnLine = 0;
for (int i = 0; i < words.size(); ++i) {
textLength += font.getStringWidthFloat(words[i]);
++ numWordsOnLine;
if ((boxWidth > 0 && textLength > boxWidth) || words[i] == "\n") { // negative boxWidth implies there is no wrapping of text by word width wise
const bool addWord = words[i] == "\n" || numWordsOnLine == 1; // add newline word to end of line, or if the only word on the line is too big to fit on the line add it to the line anyways to avoid an infinite loop
if (addWord) {
while (lineCount-1 >= lines.size()) // prevent array out of bounds crashing
lines.emplace_back("");
lines[lineCount-1] += words[i];
if (words[i] != "\n" && numWordsOnLine == 1 && i+1 < words.size() && words[i+1] == "\n") // if a newline follows the big (non-newline) word, add it to the end of the line also
lines[lineCount-1] += words[++i];
}
++ lineCount;
textLength = 0;
if (! addWord) // resume with last non-newline word that didn't fit onto the previous line (if we didn't add it above)
-- i;
numWordsOnLine = 0;
} else {
while (lineCount-1 >= lines.size()) // prevent array out of bounds crashing
lines.emplace_back("");
lines[lineCount-1] += words[i];
}
}
if (lines.size() > 0 && lines.back().size() > 0 && lines.back().back() == '\n') // if the last line's last character is a newline, tag on an empty line
lines.emplace_back("");
return lines;
}
//std::vector<std::string> TextLook::getLines(const std::string& text,
// const float boxWidth,
// const float fontSize) const
//{
// std::vector<std::string> lines;
// const auto words = parseStringIntoWords(text);
// const auto font = getFont(fontSize);
// float textLength = 0;
// int lineCount = 1;
// for (int i = 0; i < words.size(); ++i) {
// textLength += font.getStringWidthFloat(words[i]);
// if (textLength > boxWidth || words[i] == "\n") {
//// if (lines.size() > lineCount-1) // if we jump to a new line, the previous line's last whitespace is discarded
//// removeLastWhitespace(lines[lineCount-1]);
// ++lineCount;
// textLength = 0;
// if (words[i].length() > 0 && words[i][0] != ' ' && words[i] != "\n")
// --i;
// } else {
// while (lineCount-1 >= lines.size()) // prevent array out of bounds crashing
// lines.emplace_back("");
// lines[lineCount-1] += words[i];
// }
// }
// return lines;
//}
//Font TextLook::getFont(/*const float size*/) const
//{
// Font font;
// if (fontSize < 0) {
// if (multiLine) {
// const auto linesAndMaxFontSize = getLinesAndMaxFontSize(parseStringIntoWords(text),
// paddedWidth,
// paddedHeight);
// lines = linesAndMaxFontSize.first;
// font = getFont(linesAndMaxFontSize.second);
// } else {
//
// }
// } else {
// font = getFontWithSize(fontSize);
// }
// return font;
//}
Font TextLook::getFontWithSize(const float size) const
{
Font font = Font(fontName, size/* * relativeScale*/, fontStyle);
font.setExtraKerningFactor(kerning);
return font;
}
std::pair<std::vector<std::string>, Font> TextLook::getLinesAndFont(const std::string& text,
const Box& boundary,
const int windowWidth,
const int windowHeight,
const float otherFontSize,
const float otherHorizontalPad) const
{
std::vector<std::string> lines;
Font font;
const float whichFontSize = relativeScale * (otherFontSize > 0 ? otherFontSize : fontSize);
const float whichHorizontalPad = otherHorizontalPad > 0 ? otherHorizontalPad : horizontalPad;
const int w = normalizedToPixels(boundary.width() * relativeScale * whichHorizontalPad, windowWidth);
const int h = normalizedToPixels(boundary.height() * relativeScale * verticalPad, windowHeight);
if (multiLine) {
if (whichFontSize < 0) {
const auto linesAndMaxFontSize = getLinesAndMaxFontSize(parseStringIntoWords(text), w, h);
lines = linesAndMaxFontSize.first;
font = getFontWithSize(linesAndMaxFontSize.second);
} else {
lines = getLinesWithFontSize(parseStringIntoWords(text), wrap ? w : -1, whichFontSize);
font = getFontWithSize(whichFontSize);
}
} else {
// remove any newline characters if not in multiline mode
std::string textNoNewlines = text;
findAndReplace(textNoNewlines, "\n", "");
lines.emplace_back(textNoNewlines);
if (whichFontSize < 0) {
font = getFontWithSize(h);
const float size = h * std::min(w / font.getStringWidthFloat(textNoNewlines), 1.0f);
font = getFontWithSize(size);
} else
font = getFontWithSize(whichFontSize);
}
return {lines, font};
}
bool TextLook::operator == (const TextLook& other) const noexcept
{
return fontName == other.fontName &&
fontStyle == other.fontStyle &&
just == other.just &&
color == other.color &&
fontSize == other.fontSize &&
horizontalPad == other.horizontalPad &&
verticalPad == other.verticalPad &&
kerning == other.kerning &&
horizontalOffset == other.horizontalOffset &&
effects == other.effects &&
relativeScale == other.relativeScale &&
linePad == other.linePad &&
multiLine == other.multiLine &&
wrap == other.wrap;
}
bool TextLook::operator != (const TextLook& other) const noexcept
{
return fontName != other.fontName ||
fontStyle != other.fontStyle ||
just != other.just ||
color != other.color ||
fontSize != other.fontSize ||
horizontalPad != other.horizontalPad ||
verticalPad != other.verticalPad ||
kerning != other.kerning ||
horizontalOffset != other.horizontalOffset ||
effects != other.effects ||
relativeScale != other.relativeScale ||
linePad != other.linePad ||
multiLine != other.multiLine ||
wrap != other.wrap;
}
TextLook blend(const TextLook& look1,
const TextLook& look2,
const float alpha)
{
// copy over everything from the ending look
TextLook blendedLook = look2;
// interpolate the values that make sense to interpolate
blendedLook.color = look1.color.interpolatedWith(look2.color, alpha);
if (look2.fontSize >= 0 && look1.fontSize >= 0)
blendedLook.fontSize = look1.fontSize + alpha * (look2.fontSize - look1.fontSize);
blendedLook.horizontalPad = look1.horizontalPad + alpha * (look2.horizontalPad - look1.horizontalPad);
blendedLook.verticalPad = look1.verticalPad + alpha * (look2.verticalPad - look1.verticalPad);
blendedLook.kerning = look1.kerning + alpha * (look2.kerning - look1.kerning);
blendedLook.horizontalOffset = look1.horizontalOffset + alpha * (look2.horizontalOffset - look1.horizontalOffset);
blendedLook.effects.clear();
blendedLook.effects = blend(look1.effects, look2.effects, alpha);
// if (look1.effectsBehindText != look2.effectsBehindText) {
// if (look2.effectsBehindText)
// blendedLook.effectsBehindText = look1.effectsBehindText;
// else
// }
blendedLook.linePad = look1.linePad + alpha * (look2.linePad - look1.linePad);
blendedLook.relativeScale = look1.relativeScale + alpha * (look2.relativeScale - look1.relativeScale);
return blendedLook;
}
TextBox::TextBox() noexcept
: text(""), texture(Box()), look(nullptr)
{
}
TextBox::TextBox(const std::string& text,
const Box& boundary,
TextLook* look) noexcept
: text(text), texture(boundary), look(look)
{
}
void TextBox::draw(OpenGLWindow& window,
const float otherFontSize,
const float otherHorizontalPad,
std::vector<std::string>* const getLines,
Font* const getFont,
int numSpacesForTab,
const float yScrollOffset,
const float xScrollOffset,
float* const longestLineWidth)
{
look->draw(text, texture, window, otherFontSize, otherHorizontalPad, getLines, getFont, numSpacesForTab, yScrollOffset, xScrollOffset, longestLineWidth);
}
//void TextBox::draw(OpenGLWindow& window)
//{
// //if (look != nullptr)
// look->draw(text, texture, window);
//}
void TextBox::setText(const std::string& newText) noexcept
{
if (text != newText) {
text = newText;
texture.redrawToTexture = true;
}
}
std::string TextBox::getText() const noexcept
{
return text;
}
float TextBox::getTextLengthVerticallyConstrainedOnly(const int windowWidth,
const int windowHeight) const
{
auto boundary = getBoundary();
boundary.setRight(std::numeric_limits<float>::infinity());
return getLook()->getFont(getText(), boundary, windowWidth, windowHeight).getStringWidthFloat(getText());
}
float TextBox::getTextLength(const int windowWidth,
const int windowHeight) const
{
return getFont(windowWidth, windowHeight).getStringWidthFloat(getText());
}
bool TextBox::setBoundary(const Box& newBoundary) noexcept
{
if (texture.boundary != newBoundary) {
// would be nice to not have to do all the drawing work again if only the position of boundary changes...
// if (texture.boundary.width() != newBoundary.width() ||
// texture.boundary.height() != newBoundary.height())
texture.redrawToTexture = true;
texture.boundary = newBoundary;
return true;
}
return false;
}
Box TextBox::getBoundary() const noexcept
{
//const auto scale = look->relativeScale;
return texture.boundary;//getScaled(texture.boundary, scale, scale);
}
void TextBox::setLook(TextLook& newLook) noexcept
{
if (look == nullptr) {
look = &newLook;
texture.redrawToTexture = true;
} else {
if (*look != newLook) {
*look = newLook;
texture.redrawToTexture = true;
}
}
}
void TextBox::setLook(TextLook* newLook) noexcept
{
//if (look != newLook || *look != *newLook) {
look = newLook;
texture.redrawToTexture = true;
//}
}
const TextLook* TextBox::getLook() const noexcept
{
return look;
}
void TextBox::repaint() noexcept
{
texture.redrawToTexture = true;
}
bool TextBox::needsRedraw() const noexcept
{
return texture.redrawToTexture;
}
//std::pair<std::vector<std::string>, Font>
// TextBox::getTextByLineAndFont(const int windowWidth,
// const int windowHeight) const
//{
// std::vector<std::string> lines;
// Font font;
// if (look->multiLine) {
// if (look->fontSize < 0) {
// const Box paddedBoundary = getScaled(texture.boundary, look->horizontalPad, look->verticalPad);
// const int paddedWidth = myLengthToStandard(paddedBoundary.getWidth(), windowWidth);
// const int paddedHeight = myLengthToStandard(paddedBoundary.getHeight(), windowHeight);
//
// const auto linesAndMaxFontSize = look->getLinesAndMaxFontSize(parseStringIntoWords(text),
// paddedWidth, paddedHeight);
//
// lines = linesAndMaxFontSize.first;
// font = getFont(linesAndMaxFontSize.second * relativeScale);//Font(fontName, linesAndMaxFontSize.second * relativeScale, fontStyle);
// } else {
// lines = getLinesWithFontSize(parseStringIntoWords(text), boundary.getWidth(), fontSize);
// font = Font(fontName, fontSize * relativeScale, fontStyle);
// }
// } else {
// lines.emplace_back(text);
// if (fontSize < 0) {
// const float w = myLengthToStandard(boundary.getWidth() * horizontalPad, windowWidth);
// const float h = myLengthToStandard(boundary.getHeight() * verticalPad, windowHeight);
// font = Font(fontName, h, fontStyle);
// font.setExtraKerningFactor(kerning);
// const float size = h * std::min(w / font.getStringWidthFloat(text), 1.0f) * relativeScale;
// font.setSizeAndStyle(size, fontStyle, 1, kerning);
// } else
// font = Font(fontName, fontSize * relativeScale, fontStyle);
// }
// return {lines, font};
//}
Font TextBox::getFont(const int windowWidth,
const int windowHeight) const
{
return look->getFont(text, texture.boundary, windowWidth, windowHeight);
}
void makeFontsSameSize(std::vector<TextBox>& textBoxes,
const int windowWidth,
const int windowHeight)
{
// set all looks to autosize mode
for (auto& x : textBoxes) {
auto look = *x.getLook();
look.fontSize = -1;
x.setLook(look);
}
// find min font size
auto min = -1.0f;
for (const auto& x : textBoxes) {
const auto size = x.getFont(windowWidth, windowHeight).getHeight();
if (min < 0)
min = size;
else if (min > size)
min = size;
}
// ... and set all to have the min size
for (auto& x : textBoxes) {
auto look = *x.getLook();
look.fontSize = min;
x.setLook(look);
}
}
void centerAndRepositionTextBoxes(TextBox& a,
TextBox& b,
const Box& boundary,
const int windowWidth,
const int windowHeight,
const int numSpacesBetween)
{
std::vector<TextBox> boxes {a, b};
makeFontsSameSize(boxes, windowWidth, windowHeight);
const auto font = a.getFont(windowWidth, windowHeight); // assuming a and b have same font
//const auto fontB = b.getFont(windowWidth, windowHeight);
const auto widthA = pixelsToNormalized(font.getStringWidthFloat(a.getText()) / a.getLook()->horizontalPad, windowWidth);
const auto widthB = pixelsToNormalized(font.getStringWidthFloat(b.getText()) / b.getLook()->horizontalPad, windowWidth);
std::string spaces;
for (int i = 0; i < numSpacesBetween; ++i)
spaces += " ";
const auto widthSpaces = pixelsToNormalized(font.getStringWidthFloat(spaces), windowWidth);
// //const auto totalStringWidth = widthA + widthB + widthSpaces;
// const auto totalStringWidth = pixelsToNormalized(widthA + widthB + widthSpaces, windowWidth);
auto left = boundary.getLeft() + 0.5f * (boundary.width() - widthA - widthB - widthSpaces);
auto right = left + widthA;
a.setBoundary({boundary.getTop(), boundary.getBottom(), left, right});
left = right + widthSpaces;
right = left + widthB;
b.setBoundary({boundary.getTop(), boundary.getBottom(), left, right});
}
TextBoxGroup::TextBoxGroup(const std::vector<std::string>& texts,
const int numRows,
const Box& boundary,
TextLook* look,
const bool horizontallyCompress) noexcept
: numRows(numRows), boundary(boundary), fontSize(-1),
horizontallyCompress(horizontallyCompress)
{
textBoxes.resize(texts.size(), {"", {1, -1, -1, 1}, nullptr});
const int numColumns = getNumColumns(); // need textBoxes to be sized before finding numColumns
//textBoxes.reserve(texts.size());
if (horizontallyCompress && numRows == 1 && !look->multiLine) {
std::vector<float> lengths (numColumns);
float totalLength = 0;
Font font (look->fontName, 12, look->fontStyle);
font.setExtraKerningFactor(look->kerning);
for (int c = 0; c < numColumns; ++c) {
lengths[c] = font.getStringWidthFloat(texts[c]);
totalLength += lengths[c];
}
Box b {boundary.getTop(), boundary.getBottom(), boundary.getLeft(), boundary.getLeft()};
for (int c = 0; c < numColumns; ++c) {
b.setRight(b.getRight() + lengths[c] / totalLength * boundary.width());
//textBoxes.emplace_back(texts[c], b, look);
textBoxes[c] = {texts[c], b, look};
b.setLeft(b.getRight());
}
} else {
const float dW = boundary.width() / numColumns;
const float dH = boundary.height() / numRows;
Box b {boundary.getTop(), boundary.getTop() - dH, boundary.getLeft(), boundary.getLeft() + dW};
for (int r = 0; r < numRows; ++r) {
for (int c = 0; c < numColumns; ++c) {
//textBoxes.emplace_back(texts[r*numColumns+c], b, look);
textBoxes[r*numColumns+c] = {texts[r*numColumns+c], b, look};
b.setLeft(b.getLeft() + dW);
b.setRight(b.getRight() + dW);
}
b.setLeft(boundary.getLeft());
b.setRight(b.getLeft() + dW);
b.setTop(b.getTop() - dH);
b.setBottom(b.getBottom() - dH);
}
}
}
//TextBoxGroup::ScalableTextBox::ScalableTextBox(const std::string& text,
// const Box& boundary,
// TextLook* look) noexcept
// : TextBox(text, boundary, look), scale(1)
//{
//}
//
//void TextBoxGroup::ScalableTextBox::draw(OpenGLWindow& window,
// const float fontSize,
// const float horizontalPad)
//{
// //if (look != nullptr) {
// if (scale == 1)
// look->draw(text, texture, window, fontSize, horizontalPad);
// else
// look->draw(text, texture, window, -1, horizontalPad);
// //}
//}
void TextBoxGroup::draw(OpenGLWindow& window)
{
// float horizontalPad = -1;
// const bool compress = canHorizontallyCompress();
// const auto calcNHPW = [&](){
// if (compress) {
// float tot = 0;
// for (const auto& tb : textBoxes)
// tot += tb.getLook()->horizontalPad;
// return boundary.width() * (1 - tot / textBoxes.size());
// } else
// return 0.0f;
// };
// const float netHorizontalPadWidth = calcNHPW();
// const int numColumns = getNumColumns();
if (window.resized || fontSize < 0) {
float size, minSize;
for (int i = 0; i < textBoxes.size(); ++i) {
// if (compress)
// horizontalPad = 1 - netHorizontalPadWidth / (textBoxes[i].getBoundary().width() * numColumns);
size = textBoxes[i].getLook()->getFont(textBoxes[i].getText(), textBoxes[i].getBoundary(),
window.width, window.height/*, horizontalPad*/).getHeight();
if (size < minSize || i == 0)
minSize = size;
}
fontSize = minSize;
}