aboutsummaryrefslogtreecommitdiff
path: root/src/Text.cpp
blob: 14aebb162b8898ab6f7938be9190523d1ee2326b (plain)
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
#include "../include/Text.hpp"
#include "../include/ResourceLoader.hpp"
#include "../include/Config.hpp"
#include "../include/Theme.hpp"
#include "../generated/Emoji.hpp"
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Window/Clipboard.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Font.hpp>
#include <cmath>
#include <functional>

namespace QuickMedia
{
    static const float TAB_WIDTH = 4.0f;
    static const float WORD_WRAP_MIN_SIZE = 80.0f;

    static const size_t FONT_INDEX_LATIN = 0;
    static const size_t FONT_INDEX_CJK = 1;
    static const size_t FONT_INDEX_SYMBOLS = 2;
    static const size_t FONT_INDEX_EMOJI = 3;
    static const size_t FONT_ARRAY_SIZE = 4;

    size_t StringViewUtf32::find(const StringViewUtf32 &other, size_t offset) const {
        if(offset >= size)
            return -1;

        auto it = std::search(data + offset, data + size - offset, std::boyer_moore_searcher(other.data, other.data + other.size));
        if(it != data + size)
            return it - data;

        return -1;
    }
    
    Text::Text(sf::String _str, bool bold_font, unsigned int characterSize, float maxWidth, bool highlight_urls) : 
        bold_font(bold_font),
        characterSize(characterSize),
        maxWidth(maxWidth),
        color(get_theme().text_color),
        dirty(true),
        dirtyText(false),
        dirtyCaret(false),
        editable(false),
        highlight_urls(highlight_urls),
        caretMoveDirection(CaretMoveDirection::NONE),
        num_lines(1),
        lineSpacing(0.0f),
        characterSpacing(0.0f),
        caretIndex(0),
        caret_offset_x(0.0f)
    {
        for(size_t i = 0; i < FONT_ARRAY_SIZE; ++i) {
            vertices[i].setPrimitiveType(sf::PrimitiveType::Triangles);
            vertex_buffers[i] = sf::VertexBuffer(sf::PrimitiveType::Triangles, sf::VertexBuffer::Static);
        }
        setString(std::move(_str));
    }
    
    void Text::setString(const sf::String &str)
    {
        //if(str != this->str)
        //{
            size_t prev_str_size = this->str.getSize();
            this->str = str;
            dirty = true;
            dirtyText = true;
            if((int)this->str.getSize() < caretIndex || prev_str_size == 0)
            {
                caretIndex = this->str.getSize();
                dirtyCaret = true;
            }
       // }
    }
    
    const sf::String& Text::getString() const
    {
        return str;
    }

    void Text::appendText(const sf::String &str) {
        this->str += str;
        dirty = true;
        dirtyText = true;
    }
    
    void Text::setPosition(float x, float y)
    {
        position.x = x;
        position.y = y;
    }
    
    void Text::setPosition(const sf::Vector2f &position)
    {
        this->position = position;
    }
    
    sf::Vector2f Text::getPosition() const
    {
        return position;
    }
    
    // TODO: Instead of setting text to dirty, iterate vertices and change their positions
    void Text::setMaxWidth(float maxWidth)
    {
        if(std::abs(maxWidth - this->maxWidth) > 1.0f)
        {
            this->maxWidth = maxWidth;
            if(num_lines > 1 || maxWidth < boundingBox.width) {
                dirty = true;
                dirtyCaret = true;
            }
        }
    }
    
    float Text::getMaxWidth() const
    {
        return maxWidth;
    }
    
    void Text::setCharacterSize(unsigned int characterSize)
    {
        if(characterSize != this->characterSize)
        {
            this->characterSize = characterSize;
            dirty = true;
        }
    }
    
    unsigned int Text::getCharacterSize() const
    {
        return characterSize;
    }

    void Text::replace(size_t start_index, size_t length, const sf::String &insert_str) {
        int string_diff = (int)insert_str.getSize() - (int)length;
        str.replace(start_index, length, insert_str);
        dirty = true;
        dirtyText = true;
        if(caretIndex >= (int)start_index) {
            caretIndex += string_diff;
            dirtyCaret = true;
        }
    }

    int Text::getCaretIndex() const {
        return caretIndex;
    }
    
    void Text::setFillColor(sf::Color color)
    {
        if(color != this->color)
        {
            this->color = color;
            dirty = true;
        }
    }
    
    void Text::setLineSpacing(float lineSpacing)
    {
        if(fabs(lineSpacing - this->lineSpacing) > 0.001f)
        {
            this->lineSpacing = lineSpacing;
            dirty = true;
        }
    }
    
    void Text::setCharacterSpacing(float characterSpacing)
    {
        if(fabs(characterSpacing - this->characterSpacing) > 0.001f)
        {
            this->characterSpacing = characterSpacing;
            dirty = true;
        }
    }
    
    void Text::setEditable(bool editable)
    {
        if(editable != this->editable)
        {
            this->editable = editable;
            dirtyCaret = true;
            if(editable)
                dirty = true;
            else
                vertices_linear.clear();
        }
    }

    bool Text::isEditable() const {
        return editable;
    }

    void Text::moveCaretToEnd() {
        caretIndex = vertices_linear.size();
    }

    float Text::getWidth() const
    {
        return boundingBox.width;
    }
    
    float Text::getHeight() const
    {
        return boundingBox.height;
    }

    // TODO: Is there a more efficient way to do this? maybe japanese characters have a specific bit-pattern?
    static bool is_japanese_codepoint(sf::Uint32 codepoint) {
        return (codepoint >= 0x2E80 && codepoint <= 0x2FD5)     // Kanji radicals
            || (codepoint >= 0x3000 && codepoint <= 0x303F)     // Punctuation
            || (codepoint >= 0x3041 && codepoint <= 0x3096)     // Hiragana
            || (codepoint >= 0x30A0 && codepoint <= 0x30FF)     // Katakana
            || (codepoint >= 0x31F0 && codepoint <= 0x31FF)     // Miscellaneous symbols and characters 1
            || (codepoint >= 0x3220 && codepoint <= 0x3243)     // Miscellaneous symbols and characters 2
            || (codepoint >= 0x3280 && codepoint <= 0x337F)     // Miscellaneous symbols and characters 3
            || (codepoint >= 0x3400 && codepoint <= 0x4DB5)     // Kanji 1
            || (codepoint >= 0x4E00 && codepoint <= 0x9FCB)     // Kanji 2
            || (codepoint >= 0xF900 && codepoint <= 0xFA6A)     // Kanji 3
            || (codepoint >= 0xFF01 && codepoint <= 0xFF5E)     // Alphanumeric and punctuation (full width)
            || (codepoint >= 0xFF5F && codepoint <= 0xFF9F);    // Katakana and punctuation (half width)
    }

    static bool is_korean_codepoint(sf::Uint32 codepoint) {
        return codepoint >= 0xAC00 && codepoint <= 0xD7A3;
    }

    // TODO: Is there a more efficient way to do this? maybe chinese characters have a specific bit-pattern?
    static bool is_chinese_codepoint(sf::Uint32 codepoint) {
        return (codepoint >= 0x4E00 && codepoint <= 0x9FFF)     // CJK Unified Ideographs
            || (codepoint >= 0x3400 && codepoint <= 0x4DBF)     // CJK Unified Ideographs Extension A
            || (codepoint >= 0x20000 && codepoint <= 0x2A6DF)   // CJK Unified Ideographs Extension B
            || (codepoint >= 0x2A700 && codepoint <= 0x2B73F)   // CJK Unified Ideographs Extension C
            || (codepoint >= 0x2B740 && codepoint <= 0x2B81F)   // CJK Unified Ideographs Extension D
            || (codepoint >= 0x2B820 && codepoint <= 0x2CEAF)   // CJK Unified Ideographs Extension E
            || (codepoint >= 0xF900 && codepoint <= 0xFAFF)     // CJK Compatibility Ideographs
            || (codepoint >= 0x2F800 && codepoint <= 0x2FA1F);  // CJK Compatibility Ideographs Supplement
    }

    // TODO: Merge chinese, japanese and korean codepoints into one function since they share ranges
    static bool is_cjk_codepoint(sf::Uint32 codepoint) {
        return is_chinese_codepoint(codepoint) || is_japanese_codepoint(codepoint) || is_korean_codepoint(codepoint);
    }

    static bool is_symbol_codepoint(sf::Uint32 codepoint) {
        // TODO: Add the remaining NotoSansSymbols2-Regular.ttf codepoints as well.
        // See codepoint ranges with: fc-query --format='%{charset}\n' /usr/share/fonts/noto/NotoSansSymbols2-Regular.ttf.
        return codepoint >= 0x2800 && codepoint <= 0x28FF; // Braille
    }

    static size_t find_end_of_cjk(const sf::Uint32 *str, size_t size) {
        for(size_t i = 0; i < size; ++i) {
            if(!is_cjk_codepoint(str[i]))
                return i;
        }
        return size;
    }

    static size_t find_end_of_emoji(const sf::Uint32 *str, size_t size) {
        for(size_t i = 0; i < size; ++i) {
            if(!codepoint_is_emoji(str[i]))
                return i;
        }
        return size;
    }

    static size_t find_end_of_symbol(const sf::Uint32 *str, size_t size) {
        for(size_t i = 0; i < size; ++i) {
            if(!is_symbol_codepoint(str[i]))
                return i;
        }
        return size;
    }

    static size_t find_end_latin(const sf::Uint32 *str, size_t size) {
        for(size_t i = 0; i < size; ++i) {
            if(is_cjk_codepoint(str[i]) || codepoint_is_emoji(str[i]) || is_symbol_codepoint(str[i]))
                return i;
        }
        return size;
    }

    void Text::splitTextByFont() {
        textElements.clear();
        size_t index = 0;
        size_t size = str.getSize();
        while(index < size) {
            size_t offset;
            TextElement::TextType text_type = TextElement::TextType::LATIN;
            if(is_symbol_codepoint(str[index])) {
                text_type = TextElement::TextType::SYMBOL;
                offset = find_end_of_symbol(str.getData() + index + 1, size - index - 1);
            } else if(is_cjk_codepoint(str[index])) {
                text_type = TextElement::TextType::CJK;
                offset = find_end_of_cjk(str.getData() + index + 1, size - index - 1);
            } else if(codepoint_is_emoji(str[index])) {
                text_type = TextElement::TextType::EMOJI;
                offset = find_end_of_emoji(str.getData() + index + 1, size - index - 1);
            } else {
                offset = find_end_latin(str.getData() + index + 1, size - index - 1);
            }
            textElements.push_back({ StringViewUtf32(str.getData() + index, offset + 1), TextElement::Type::TEXT });
            textElements.back().text_type = text_type;
            index += 1 + offset;
        }
    }

    float Text::font_get_real_height(sf::Font *font) {
        return font->getGlyph('|', characterSize, false).bounds.height + std::floor(4.0f * ((float)characterSize / (float)14.0f));
    }

    float Text::get_text_quad_left_side(const VertexRef &vertex_ref) const {
        return vertices[vertex_ref.vertices_index][vertex_ref.index + 1].position.x;
    }

    float Text::get_text_quad_right_side(const VertexRef &vertex_ref) const {
        return vertices[vertex_ref.vertices_index][vertex_ref.index + 5].position.x;
    }

    float Text::get_caret_offset_by_caret_index(int index) const {
        const int num_vertices = vertices_linear.size();
        if(num_vertices == 0)
            return 0.0f;
        else if(index < num_vertices)
            return get_text_quad_left_side(vertices_linear[index]);
        else
            return get_text_quad_right_side(vertices_linear[num_vertices - 1]);
    }

    VertexRef& Text::get_vertex_ref_clamp(int index) {
        const int num_vertices = vertices_linear.size();
        assert(num_vertices > 0);
        if(index == num_vertices)
            return vertices_linear.back();
        else
            return vertices_linear[index];
    }

    int Text::get_vertex_line(int index) const {
        const int num_vertices = vertices_linear.size();
        if(num_vertices == 0) {
            return 0;
        } else if(index < num_vertices) {
            return vertices_linear[index].line;
        } else {
            if(vertices_linear.back().codepoint == '\n')
                return vertices_linear.back().line + 1;
            else
                return vertices_linear.back().line;
        }
    }

    sf::Uint32 Text::get_vertex_codepoint(int index) const {
        const int num_vertices = vertices_linear.size();
        if(num_vertices == 0) {
            return 0;
        } else if(index < num_vertices) {
            return vertices_linear[index].codepoint;
        } else {
            return vertices_linear.back().codepoint;
        }
    }
    
    void Text::updateGeometry(bool update_even_if_not_dirty) {
        if(dirtyText) {
            assert(dirty);
            dirtyText = false;
            splitTextByFont();
            // TODO: Optimize
            if(highlight_urls) {
                auto u8 = str.toUtf8();
                std::string *u8_str = (std::string*)&u8;
                url_ranges = extract_urls(*u8_str);
                convert_utf8_to_utf32_ranges(*u8_str, url_ranges);
            } else {
                url_ranges.clear();
            }
        }

        if(!update_even_if_not_dirty && !dirty)
            return;

        dirty = false;
        vertices_linear.clear();
        for(size_t i = 0; i < FONT_ARRAY_SIZE; ++i) {
            vertices[i].clear();
            vertices[i].resize(0);
        }
        boundingBox = sf::FloatRect();

        sf::Font *latin_font;
        if(bold_font)
            latin_font = FontLoader::get_font(FontLoader::FontType::LATIN_BOLD);
        else
            latin_font = FontLoader::get_font(FontLoader::FontType::LATIN);

        const float latin_font_width = latin_font->getGlyph(' ', characterSize, false).advance;
        const float hspace = latin_font_width + characterSpacing;
        const float vspace = font_get_real_height(latin_font);
        const float emoji_scale = vspace / 20.0f;

        const sf::Color url_color = get_theme().url_text_color;

        size_t url_range_index = 0;
        
        sf::Vector2f glyphPos;
        sf::Uint32 prevCodePoint = 0;
        // TODO: Only do this if dirtyText (then the Text object shouldn't be reset in Body. There should be a cleanup function in text instead)
        for(usize textElementIndex = 0; textElementIndex < textElements.size(); ++textElementIndex)
        {
            TextElement &textElement = textElements[textElementIndex];
            const sf::Font *ff = latin_font;
            int vertices_index = FONT_INDEX_LATIN;
            prevCodePoint = 0;
            if(textElement.text_type == TextElement::TextType::CJK) {
                ff = FontLoader::get_font(FontLoader::FontType::CJK);
                vertices_index = FONT_INDEX_CJK;
            } else if(textElement.text_type == TextElement::TextType::SYMBOL) {
                ff = FontLoader::get_font(FontLoader::FontType::SYMBOLS);
                vertices_index = FONT_INDEX_SYMBOLS;
            } else if(textElement.text_type == TextElement::TextType::EMOJI) {
                vertices_index = FONT_INDEX_EMOJI;
                textElement.position = glyphPos;
                sf::Color emoji_color(255, 255, 255, color.a);
                for(size_t i = 0; i < textElement.text.size; ++i)
                {
                    sf::Uint32 codePoint = textElement.text[i];
                    int vertexStart = vertices[vertices_index].getVertexCount();
                    EmojiRectangle emoji_rec = emoji_get_extents(codePoint);
                
                    const float font_height_offset = std::floor(-vspace * 0.2f);
                    sf::Vector2f vertexTopLeft(glyphPos.x, glyphPos.y + font_height_offset - std::floor(emoji_rec.height * emoji_scale) * 0.5f);
                    sf::Vector2f vertexTopRight(glyphPos.x + std::floor(emoji_rec.width * emoji_scale), glyphPos.y + font_height_offset - std::floor(emoji_rec.height * emoji_scale) * 0.5f);
                    sf::Vector2f vertexBottomLeft(glyphPos.x, glyphPos.y + font_height_offset + emoji_rec.height * emoji_scale * 0.5f);
                    sf::Vector2f vertexBottomRight(glyphPos.x + std::floor(emoji_rec.width * emoji_scale), glyphPos.y + font_height_offset + std::floor(emoji_rec.height * emoji_scale) * 0.5f);
                    
                    sf::Vector2f textureTopLeft(emoji_rec.x, emoji_rec.y);
                    sf::Vector2f textureTopRight(emoji_rec.x + emoji_rec.width, emoji_rec.y);
                    sf::Vector2f textureBottomLeft(emoji_rec.x, emoji_rec.y + emoji_rec.height);
                    sf::Vector2f textureBottomRight(emoji_rec.x + emoji_rec.width, emoji_rec.y + emoji_rec.height);
                    
                    vertices[vertices_index].append({ vertexTopRight, emoji_color, textureTopRight });
                    vertices[vertices_index].append({ vertexTopLeft, emoji_color, textureTopLeft });
                    vertices[vertices_index].append({ vertexBottomLeft, emoji_color, textureBottomLeft });
                    vertices[vertices_index].append({ vertexBottomLeft, emoji_color, textureBottomLeft });
                    vertices[vertices_index].append({ vertexBottomRight, emoji_color, textureBottomRight });
                    vertices[vertices_index].append({ vertexTopRight, emoji_color, textureTopRight });
                    
                    glyphPos.x += std::floor(emoji_rec.width * emoji_scale) + characterSpacing;
                    vertices_linear.push_back({vertices_index, vertexStart, 0, codePoint});
                }
                continue;
            }
            
            //vertices[vertices_index].resize(vertices[vertices_index].getVertexCount() + 4 * textElement.text.size); // TODO: Precalculate
            textElement.position = glyphPos;
            for(size_t i = 0; i < textElement.text.size; ++i)
            {
                sf::Color text_color = color;
                if(url_range_index < url_ranges.size()) {
                    size_t string_offset = (textElement.text.data + i) - str.getData();
                    if(string_offset >= url_ranges[url_range_index].start && string_offset < url_ranges[url_range_index].start + url_ranges[url_range_index].length) {
                        text_color = url_color;
                        text_color.a = color.a;
                        if(string_offset + 1 == url_ranges[url_range_index].start + url_ranges[url_range_index].length)
                            ++url_range_index;
                    }
                }

                sf::Uint32 codePoint = textElement.text[i];
                // TODO: Make this work when combining multiple different fonts (for example latin and japanese).
                // For japanese we could use a hack, because all japanese characters are monospace (exception being half-width characters).
                float kerning = ff->getKerning(prevCodePoint, codePoint, characterSize);
                prevCodePoint = codePoint;
                glyphPos.x += kerning;
                
                int vertexStart = vertices[vertices_index].getVertexCount();
                
                switch(codePoint)
                {
                    case ' ':
                    {
                        sf::Vector2f vertexTopLeft(glyphPos.x, glyphPos.y - vspace);
                        sf::Vector2f vertexTopRight(glyphPos.x + hspace, glyphPos.y - vspace);
                        sf::Vector2f vertexBottomLeft(glyphPos.x, glyphPos.y);
                        sf::Vector2f vertexBottomRight(glyphPos.x + hspace, glyphPos.y);

                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });

                        glyphPos.x += hspace;
                        vertices_linear.push_back({vertices_index, vertexStart, 0, codePoint});
                        continue;
                    }
                    case '\t':
                    {
                        const float char_width = hspace * TAB_WIDTH;
                        sf::Vector2f vertexTopLeft(glyphPos.x, glyphPos.y - vspace);
                        sf::Vector2f vertexTopRight(glyphPos.x + char_width, glyphPos.y - vspace);
                        sf::Vector2f vertexBottomLeft(glyphPos.x, glyphPos.y);
                        sf::Vector2f vertexBottomRight(glyphPos.x + char_width, glyphPos.y);

                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });

                        glyphPos.x += char_width;
                        vertices_linear.push_back({vertices_index, vertexStart, 0, codePoint});
                        continue;
                    }
                    case '\n':
                    {
                        sf::Vector2f vertexTopLeft(glyphPos.x, glyphPos.y - vspace);
                        sf::Vector2f vertexTopRight(glyphPos.x, glyphPos.y - vspace);
                        sf::Vector2f vertexBottomLeft(glyphPos.x, glyphPos.y);
                        sf::Vector2f vertexBottomRight(glyphPos.x, glyphPos.y);

                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomLeft, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexBottomRight, sf::Color::Transparent, sf::Vector2f() });
                        vertices[vertices_index].append({ vertexTopRight, sf::Color::Transparent, sf::Vector2f() });

                        glyphPos.x = 0.0f;
                        glyphPos.y += floor(vspace + lineSpacing);
                        vertices_linear.push_back({vertices_index, vertexStart, 0, codePoint});
                        continue;
                    }
                }
                
                const sf::Glyph &glyph = ff->getGlyph(codePoint, characterSize, false);
                
                sf::Vector2f vertexTopLeft(glyphPos.x + glyph.bounds.left, glyphPos.y + glyph.bounds.top);
                sf::Vector2f vertexTopRight(glyphPos.x + glyph.bounds.left + glyph.bounds.width, glyphPos.y + glyph.bounds.top);
                sf::Vector2f vertexBottomLeft(glyphPos.x + glyph.bounds.left, glyphPos.y + glyph.bounds.top + glyph.bounds.height);
                sf::Vector2f vertexBottomRight(glyphPos.x + glyph.bounds.left + glyph.bounds.width, glyphPos.y + glyph.bounds.top + glyph.bounds.height);
                
                sf::Vector2f textureTopLeft(glyph.textureRect.left, glyph.textureRect.top);
                sf::Vector2f textureTopRight(glyph.textureRect.left + glyph.textureRect.width, glyph.textureRect.top);
                sf::Vector2f textureBottomLeft(glyph.textureRect.left, glyph.textureRect.top + glyph.textureRect.height);
                sf::Vector2f textureBottomRight(glyph.textureRect.left + glyph.textureRect.width, glyph.textureRect.top + glyph.textureRect.height);
                
                vertices[vertices_index].append({ vertexTopRight, text_color, textureTopRight });
                vertices[vertices_index].append({ vertexTopLeft, text_color, textureTopLeft });
                vertices[vertices_index].append({ vertexBottomLeft, text_color, textureBottomLeft });
                vertices[vertices_index].append({ vertexBottomLeft, text_color, textureBottomLeft });
                vertices[vertices_index].append({ vertexBottomRight, text_color, textureBottomRight });
                vertices[vertices_index].append({ vertexTopRight, text_color, textureTopRight });
                
                glyphPos.x += glyph.advance + characterSpacing;
                vertices_linear.push_back({vertices_index, vertexStart, 0, codePoint});
            }
        }

        const float line_height = floor(vspace + lineSpacing);
        float text_wrap_offset = 0.0f;
        float text_offset_y = 0.0f;
        int last_space_index = -1;
        num_lines = 1;
        // TODO: Binary search?
        for(int i = 0; i < (int)vertices_linear.size(); ++i) {
            VertexRef &vertex_ref = vertices_linear[i];

            sf::Vertex *vertex = &vertices[vertex_ref.vertices_index][vertex_ref.index];
            for(int v = 0; v < 6; ++v) {
                vertex[v].position.x -= text_wrap_offset;
                vertex[v].position.y += text_offset_y;
            }
            vertex_ref.line = num_lines - 1;

            switch(vertex_ref.codepoint) {
                case ' ':
                case '\t':
                    last_space_index = i;
                    break;
                case '\n':
                    text_wrap_offset = 0.0f;
                    last_space_index = -1;
                    ++num_lines;
                    break;
                default:
                    break;
            }

            float vertex_right_side = get_text_quad_right_side(vertex_ref);
            if(vertex_right_side > maxWidth && maxWidth > WORD_WRAP_MIN_SIZE) {
                ++num_lines;
                // TODO: Ignore line wrap on space
                if(last_space_index != -1 && last_space_index != i) {
                    float vertex_left_side = get_text_quad_left_side(vertices_linear[last_space_index + 1]);
                    for(int j = last_space_index + 1; j <= i; ++j) {
                        VertexRef &vertex_ref_wrap = vertices_linear[j];
                        sf::Vertex *vertex = &vertices[vertex_ref_wrap.vertices_index][vertex_ref_wrap.index];
                        for(int v = 0; v < 6; ++v) {
                            vertex[v].position.x -= vertex_left_side;
                            vertex[v].position.y += line_height;
                        }
                        vertex_ref_wrap.line = num_lines - 1;
                    }
                    last_space_index = -1;
                    text_wrap_offset += vertex_left_side;
                } else {
                    float vertex_left_side = get_text_quad_left_side(vertex_ref);
                    for(int v = 0; v < 6; ++v) {
                        vertex[v].position.x -= vertex_left_side;
                        vertex[v].position.y += line_height;
                    }

                    text_wrap_offset += vertex_left_side;
                    vertex_ref.line = num_lines - 1;
                }
                text_offset_y += line_height;
            }
        }

        boundingBox.width = 0.0f;
        for(VertexRef &vertex_ref : vertices_linear) {
            boundingBox.width = std::max(boundingBox.width, get_text_quad_right_side(vertex_ref));
        }
        boundingBox.height = num_lines * line_height;

        // TODO: Clear |vertices| somehow even with editable text
        for(size_t i = 0; i < FONT_ARRAY_SIZE; ++i) {
            vertex_buffers[i].create(vertices[i].getVertexCount());
            if(vertices[i].getVertexCount() > 0)
                vertex_buffers[i].update(&vertices[i][0], vertices[i].getVertexCount(), 0);
        }

        //url_ranges.clear();
        if(!editable) {
            for(size_t i = 0; i < FONT_ARRAY_SIZE; ++i) {
                vertices[i].clear();
                vertices[i].resize(0);
            }
            vertices_linear.clear();
            vertices_linear.shrink_to_fit();
        }
    }

    void Text::updateCaret()
    {
        assert(!dirty && !dirtyText);

        sf::Font *latin_font;
        if(bold_font)
            latin_font = FontLoader::get_font(FontLoader::FontType::LATIN_BOLD);
        else
            latin_font = FontLoader::get_font(FontLoader::FontType::LATIN);

        const float vspace = font_get_real_height(latin_font);

        if(vertices_linear.empty()) {
            caretIndex = 0;
            caretPosition = sf::Vector2f(0.0f, floor(vspace));
            caret_offset_x = 0.0f;
            return;
        }

        switch(caretMoveDirection) {
            case CaretMoveDirection::NONE: {
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::UP: {
                caretIndex = getPreviousLineClosestPosition(caretIndex);
                break;
            }
            case CaretMoveDirection::DOWN: {
                caretIndex = getNextLineClosestPosition(caretIndex);
                break;
            }
            case CaretMoveDirection::HOME: {
                caretIndex = getStartOfLine(caretIndex);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::END: {
                caretIndex = getEndOfLine(caretIndex);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::LEFT: {
                caretIndex = std::max(0, caretIndex - 1);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::RIGHT: {
                caretIndex = std::min((int)vertices_linear.size(), caretIndex + 1);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::LEFT_WORD: {
                caretIndex = getStartOfWord(caretIndex);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
            case CaretMoveDirection::RIGHT_WORD: {
                caretIndex = getEndOfWord(caretIndex);
                caret_offset_x = get_caret_offset_by_caret_index(caretIndex);
                break;
            }
        }

        if(caretIndex == (int)vertices_linear.size()) {
            VertexRef &last_vertex = get_vertex_ref_clamp(caretIndex);
            if(last_vertex.codepoint == '\n')
                caretPosition.x = 0.0f;
            else
                caretPosition.x = get_text_quad_right_side(last_vertex);
            caretPosition.y = (1 + get_vertex_line(caretIndex)) * floor(vspace + lineSpacing);
        } else {
            caretPosition.x = get_caret_offset_by_caret_index(caretIndex);
            caretPosition.y = (1 + get_vertex_line(caretIndex)) * floor(vspace + lineSpacing);
        }
    }

    // TODO: This can be optimized by using binary search
    int Text::getStartOfLine(int startIndex) const
    {
        assert(!dirty && !dirtyText);
        int start_line = get_vertex_line(startIndex);
        for(int i = startIndex - 1; i >= 0; --i) {
            if(get_vertex_line(i) != start_line) {
                return i + 1;
            }
        }
        return 0;
    }
    
    // TODO: This can be optimized by using binary search
    int Text::getEndOfLine(int startIndex) const
    {
        assert(!dirty && !dirtyText);
        const int num_vertices = vertices_linear.size();
        int start_line = get_vertex_line(startIndex);
        for(int i = startIndex + 1; i < num_vertices; ++i) {
            if(get_vertex_line(i) != start_line) {
                return i - 1;
            }
        }
        return num_vertices;
    }

    static bool is_special_character(sf::Uint32 codepoint) {
        return (codepoint <= 47) || (codepoint >= 58 && codepoint <= 64) || (codepoint >= 91 && codepoint <= 96) || (codepoint >= 123 && codepoint <= 127);
    }

    int Text::getStartOfWord(int startIndex) const {
        assert(!dirty && !dirtyText);
        bool start_is_special_char = is_special_character(get_vertex_codepoint(startIndex - 1));
        for(int i = startIndex - 1; i >= 0; --i) {
            bool is_special_char = is_special_character(vertices_linear[i].codepoint);
            if(is_special_char != start_is_special_char)
                return i + 1;
        }
        return 0;
    }

    int Text::getEndOfWord(int startIndex) const {
        assert(!dirty && !dirtyText);
        const int num_vertices = vertices_linear.size();
        bool start_is_special_char = is_special_character(get_vertex_codepoint(startIndex));
        for(int i = startIndex + 1; i < num_vertices; ++i) {
            bool is_special_char = is_special_character(vertices_linear[i].codepoint);
            if(is_special_char != start_is_special_char)
                return i;
        }
        return num_vertices;
    }
    
    // TODO: This can be optimized by using binary search
    int Text::getPreviousLineClosestPosition(int startIndex) const
    {
        assert(!dirty && !dirtyText);
        const int start_line = get_vertex_line(startIndex);
        float closest_char = 999999.9f;
        int closest_index = -1;
        for(int i = getStartOfLine(startIndex) - 1; i >= 0 && get_vertex_line(i) == start_line - 1; --i) {
            const float left_pos = get_text_quad_left_side(vertices_linear[i]);
            const float pos_diff = std::abs(caret_offset_x - left_pos);
            if(pos_diff < closest_char) {
                closest_char = pos_diff;
                closest_index = i;
            }
        }
        if(closest_index != -1)
            return closest_index;
        return startIndex;
    }
    
    // TODO: This can be optimized by using binary search
    int Text::getNextLineClosestPosition(int startIndex) const
    {
        assert(!dirty && !dirtyText);
        const int num_vertices = vertices_linear.size();
        const int start_line = get_vertex_line(startIndex);
        float closest_char = 999999.9f;
        int closest_index = -1;
        for(int i = getEndOfLine(startIndex) + 1; i < num_vertices && get_vertex_line(i) == start_line + 1; ++i) {
            const float left_pos = get_text_quad_left_side(vertices_linear[i]);
            const float pos_diff = std::abs(caret_offset_x - left_pos);
            if(pos_diff < closest_char) {
                closest_char = pos_diff;
                closest_index = i;
            }
        }
        if(closest_index != -1)
            return closest_index;
        return startIndex;
    }

    // TODO: Optimize text editing by only processing the changed parts in updateGeometry.
    // TODO: Split text into lines and add to vertices list so the lines that are cut off are not visible. This is good when using the text and as text input
    // where there are a max number of rows shown at a time.
    void Text::processEvent(const sf::Event &event)
    {
        if(!editable) return;
        
        bool caretAtEnd = caretIndex == (int)vertices_linear.size();
        
        if(event.type == sf::Event::KeyPressed)
        {
            if(event.key.code == sf::Keyboard::Left && caretIndex > 0)
            {
                if(event.key.control)
                    caretMoveDirection = CaretMoveDirection::LEFT_WORD;
                else
                    caretMoveDirection = CaretMoveDirection::LEFT;
                dirtyCaret = true;
            }
            else if(event.key.code == sf::Keyboard::Right && !caretAtEnd)
            {
                if(event.key.control)
                    caretMoveDirection = CaretMoveDirection::RIGHT_WORD;
                else
                    caretMoveDirection = CaretMoveDirection::RIGHT;
                dirtyCaret = true;
            }
            else if(event.key.code == sf::Keyboard::BackSpace && caretIndex > 0)
            {
                str.erase(caretIndex - 1, 1);
                --caretIndex;
                dirty = true;
                dirtyText = true;
                dirtyCaret = true;
            }
            else if(event.key.code == sf::Keyboard::Delete && !caretAtEnd)
            {
                str.erase(caretIndex, 1);
                dirty = true;
                dirtyText = true;
            }
            else if(event.key.code == sf::Keyboard::D && event.key.control)
            {
                setString("");
            }
            else if(event.key.code == sf::Keyboard::Up)
            {
                caretMoveDirection = CaretMoveDirection::UP;
            }
            else if(event.key.code == sf::Keyboard::Down)
            {
                caretMoveDirection = CaretMoveDirection::DOWN;
            }
            else if(event.key.code == sf::Keyboard::Home)
            {
                caretMoveDirection = CaretMoveDirection::HOME;
            }
            else if(event.key.code == sf::Keyboard::End)
            {
                caretMoveDirection = CaretMoveDirection::END;
            }
            else if(event.key.code == sf::Keyboard::Enter)
            {
                if(event.key.shift && !single_line_edit)
                {
                    if(caretAtEnd)
                        str += '\n';
                    else
                        str.insert(caretIndex, '\n');
                    
                    ++caretIndex;
                    dirty = true;
                    dirtyText = true;
                    dirtyCaret = true;
                }
            }
        }
        else if(event.type == sf::Event::TextEntered)
        {
            if(event.text.unicode == 8 || event.text.unicode == 127) // backspace, del
                return;
            
            sf::String stringToAdd;
            if(event.text.unicode == 22) // ctrl+v
            {
                stringToAdd = sf::Clipboard::getString();
            }
            else if(event.text.unicode >= 32 || (event.text.unicode == '\t' && !single_line_edit)) 
                stringToAdd = event.text.unicode;
            else
                return;
            
            if(caretAtEnd)
                str += stringToAdd;
            else
                str.insert(caretIndex, stringToAdd);
            
            caretIndex += stringToAdd.getSize();
            dirty = true;
            dirtyText = true;
            dirtyCaret = true;
        }
    }

    bool Text::draw(sf::RenderTarget &target)
    {
        updateGeometry();

        if(editable && (dirtyCaret || caretMoveDirection != CaretMoveDirection::NONE)) {
            updateCaret();
            dirtyCaret = false;
            caretMoveDirection = CaretMoveDirection::NONE;
        }
        
        sf::Vector2f pos = position;

        FontLoader::FontType latin_font_type;
        if(bold_font)
            latin_font_type = FontLoader::FontType::LATIN_BOLD;
        else
            latin_font_type = FontLoader::FontType::LATIN;
        sf::Font *latin_font = FontLoader::get_font(latin_font_type);

        const float vspace = font_get_real_height(latin_font);
        pos.y += floor(vspace); // Origin is at bottom left, we want it to be at top left
        
        const FontLoader::FontType font_types[] = { latin_font_type, FontLoader::FontType::CJK, FontLoader::FontType::SYMBOLS };
        for(size_t i = 0; i < FONT_INDEX_EMOJI; ++i) {
            if(vertex_buffers[i].getVertexCount() == 0)
                continue;

            sf::Font *font = FontLoader::get_font(font_types[i]);
            sf::RenderStates states;
            states.transform.translate(pos);
            states.texture = &font->getTexture(characterSize);
            target.draw(vertex_buffers[i], states);
        }

        if(vertex_buffers[FONT_INDEX_EMOJI].getVertexCount() > 0) {
            sf::RenderStates states;
            states.transform.translate(pos);
            states.texture = TextureLoader::get_texture("images/emoji.png");
            target.draw(vertex_buffers[FONT_INDEX_EMOJI], states);
        }
        
        if(!editable) return true;
        pos.y -= floor(vspace * 2.0f);

        const float caret_margin = std::floor(2.0f * get_config().scale);

        sf::RectangleShape caretRect(sf::Vector2f(std::floor(2.0f * get_config().scale), floor(vspace - caret_margin * 2.0f)));
        caretRect.setPosition(floor(pos.x + caretPosition.x), floor(pos.y + caretPosition.y + caret_margin + std::floor(4.0f * get_config().scale)));
        target.draw(caretRect);
        return true;
    }
}