-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathtext.cpp
3448 lines (3091 loc) · 99.9 KB
/
text.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
// This file is part of Desktop App Toolkit,
// a set of libraries for developing nice desktop applications.
//
// For license and copyright information please follow this link:
// https://github.com/desktop-app/legal/blob/master/LEGAL
//
#include "ui/text/text.h"
#include "ui/basic_click_handlers.h"
#include "ui/text/text_block.h"
#include "ui/text/text_isolated_emoji.h"
#include "ui/emoji_config.h"
#include "ui/integration.h"
#include "base/platform/base_platform_info.h"
#include <private/qfontengine_p.h>
#include <private/qharfbuzz_p.h>
namespace Ui {
namespace Text {
namespace {
constexpr auto kStringLinkIndexShift = uint16(0x8000);
constexpr auto kMaxDiacAfterSymbol = 2;
Qt::LayoutDirection StringDirection(
const QString &str,
int from,
int to) {
auto p = reinterpret_cast<const ushort*>(str.unicode()) + from;
const auto end = p + (to - from);
while (p < end) {
uint ucs4 = *p;
if (QChar::isHighSurrogate(ucs4) && p < end - 1) {
ushort low = p[1];
if (QChar::isLowSurrogate(low)) {
ucs4 = QChar::surrogateToUcs4(ucs4, low);
++p;
}
}
switch (QChar::direction(ucs4)) {
case QChar::DirL:
return Qt::LeftToRight;
case QChar::DirR:
case QChar::DirAL:
return Qt::RightToLeft;
default:
break;
}
++p;
}
return Qt::LayoutDirectionAuto;
}
TextWithEntities PrepareRichFromPlain(
const QString &text,
const TextParseOptions &options) {
auto result = TextWithEntities{ text };
if (options.flags & TextParseLinks) {
TextUtilities::ParseEntities(
result,
options.flags,
(options.flags & TextParseRichText));
}
return result;
}
TextWithEntities PrepareRichFromRich(
const TextWithEntities &text,
const TextParseOptions &options) {
auto result = text;
const auto &preparsed = text.entities;
if ((options.flags & TextParseLinks) && !preparsed.isEmpty()) {
bool parseMentions = (options.flags & TextParseMentions);
bool parseHashtags = (options.flags & TextParseHashtags);
bool parseBotCommands = (options.flags & TextParseBotCommands);
bool parseMarkdown = (options.flags & TextParseMarkdown);
if (!parseMentions || !parseHashtags || !parseBotCommands || !parseMarkdown) {
int32 i = 0, l = preparsed.size();
result.entities.clear();
result.entities.reserve(l);
const QChar s = result.text.size();
for (; i < l; ++i) {
auto type = preparsed.at(i).type();
if (((type == EntityType::Mention || type == EntityType::MentionName) && !parseMentions) ||
(type == EntityType::Hashtag && !parseHashtags) ||
(type == EntityType::Cashtag && !parseHashtags) ||
(type == EntityType::BotCommand && !parseBotCommands) || // #TODO entities
(!parseMarkdown && (type == EntityType::Bold
|| type == EntityType::Semibold
|| type == EntityType::Italic
|| type == EntityType::Underline
|| type == EntityType::StrikeOut
|| type == EntityType::Code
|| type == EntityType::Pre))) {
continue;
}
result.entities.push_back(preparsed.at(i));
}
}
}
return result;
}
QFixed ComputeStopAfter(
const TextParseOptions &options,
const style::TextStyle &st) {
return (options.maxw > 0 && options.maxh > 0)
? ((options.maxh / st.font->height) + 1) * options.maxw
: QFIXED_MAX;
}
// Open Sans tilde fix.
bool ComputeCheckTilde(const style::TextStyle &st) {
const auto &font = st.font;
return (font->size() * style::DevicePixelRatio() == 13)
&& (font->flags() == 0)
&& (font->f.family() == qstr("DAOpenSansRegular"));
}
bool IsParagraphSeparator(QChar ch) {
switch (ch.unicode()) {
case QChar::LineFeed:
return true;
default:
break;
}
return false;
}
bool IsBad(QChar ch) {
return (ch == 0)
|| (ch >= 8232 && ch < 8237)
|| (ch >= 65024 && ch < 65040 && ch != 65039)
|| (ch >= 127 && ch < 160 && ch != 156)
// qt harfbuzz crash see https://github.com/telegramdesktop/tdesktop/issues/4551
|| (Platform::IsMac() && ch == 6158)
// tmp hack see https://bugreports.qt.io/browse/QTBUG-48910
|| (Platform::IsMac10_11OrGreater()
&& !Platform::IsMac10_12OrGreater()
&& ch >= 0x0B00
&& ch <= 0x0B7F
&& IsDiac(ch));
}
} // namespace
} // namespace Text
} // namespace Ui
QString textcmdSkipBlock(ushort w, ushort h) {
static QString cmd(5, TextCommand);
cmd[1] = QChar(TextCommandSkipBlock);
cmd[2] = QChar(w);
cmd[3] = QChar(h);
return cmd;
}
QString textcmdStartLink(ushort lnkIndex) {
static QString cmd(4, TextCommand);
cmd[1] = QChar(TextCommandLinkIndex);
cmd[2] = QChar(lnkIndex);
return cmd;
}
QString textcmdStartLink(const QString &url) {
if (url.size() >= 4096) return QString();
QString result;
result.reserve(url.size() + 4);
return result.append(TextCommand).append(QChar(TextCommandLinkText)).append(QChar(url.size())).append(url).append(TextCommand);
}
QString textcmdStopLink() {
return textcmdStartLink(0);
}
QString textcmdLink(ushort lnkIndex, const QString &text) {
QString result;
result.reserve(4 + text.size() + 4);
return result.append(textcmdStartLink(lnkIndex)).append(text).append(textcmdStopLink());
}
QString textcmdLink(const QString &url, const QString &text) {
QString result;
result.reserve(4 + url.size() + text.size() + 4);
return result.append(textcmdStartLink(url)).append(text).append(textcmdStopLink());
}
QString textcmdStartSemibold() {
QString result;
result.reserve(3);
return result.append(TextCommand).append(QChar(TextCommandSemibold)).append(TextCommand);
}
QString textcmdStopSemibold() {
QString result;
result.reserve(3);
return result.append(TextCommand).append(QChar(TextCommandNoSemibold)).append(TextCommand);
}
const QChar *textSkipCommand(const QChar *from, const QChar *end, bool canLink) {
const QChar *result = from + 1;
if (*from != TextCommand || result >= end) return from;
ushort cmd = result->unicode();
++result;
if (result >= end) return from;
switch (cmd) {
case TextCommandBold:
case TextCommandNoBold:
case TextCommandSemibold:
case TextCommandNoSemibold:
case TextCommandItalic:
case TextCommandNoItalic:
case TextCommandUnderline:
case TextCommandNoUnderline:
break;
case TextCommandLinkIndex:
if (result->unicode() > 0x7FFF) return from;
++result;
break;
case TextCommandLinkText: {
ushort len = result->unicode();
if (len >= 4096 || !canLink) return from;
result += len + 1;
} break;
case TextCommandSkipBlock:
result += 2;
break;
case TextCommandLangTag:
result += 1;
break;
}
return (result < end && *result == TextCommand) ? (result + 1) : from;
}
const TextParseOptions _defaultOptions = {
TextParseLinks | TextParseMultiline, // flags
0, // maxw
0, // maxh
Qt::LayoutDirectionAuto, // dir
};
const TextParseOptions _textPlainOptions = {
TextParseMultiline, // flags
0, // maxw
0, // maxh
Qt::LayoutDirectionAuto, // dir
};
namespace Ui {
namespace Text {
class Parser {
public:
Parser(
not_null<String*> string,
const QString &text,
const TextParseOptions &options,
const std::any &context);
Parser(
not_null<String*> string,
const TextWithEntities &textWithEntities,
const TextParseOptions &options,
const std::any &context);
private:
struct ReadyToken {
};
class StartedEntity {
public:
explicit StartedEntity(TextBlockFlags flags);
explicit StartedEntity(uint16 lnkIndex);
std::optional<TextBlockFlags> flags() const;
std::optional<uint16> lnkIndex() const;
private:
int _value = 0;
};
Parser(
not_null<String*> string,
TextWithEntities &&source,
const TextParseOptions &options,
const std::any &context,
ReadyToken);
void trimSourceRange();
void blockCreated();
void createBlock(int32 skipBack = 0);
void createSkipBlock(int32 w, int32 h);
void createNewlineBlock();
bool checkCommand();
// Returns true if at least one entity was parsed in the current position.
bool checkEntities();
bool readSkipBlockCommand();
bool readCommand();
void parseCurrentChar();
void parseEmojiFromCurrent();
void checkForElidedSkipBlock();
void finalize(const TextParseOptions &options);
void finishEntities();
void skipPassedEntities();
void skipBadEntities();
bool isInvalidEntity(const EntityInText &entity) const;
bool isLinkEntity(const EntityInText &entity) const;
void parse(const TextParseOptions &options);
void computeLinkText(
const QString &linkData,
QString *outLinkText,
EntityLinkShown *outShown);
const not_null<String*> _t;
const TextWithEntities _source;
const std::any &_context;
const QChar * const _start = nullptr;
const QChar *_end = nullptr; // mutable, because we trim by decrementing.
const QChar *_ptr = nullptr;
const EntitiesInText::const_iterator _entitiesEnd;
EntitiesInText::const_iterator _waitingEntity;
const bool _rich = false;
const bool _multiline = false;
const QFixed _stopAfterWidth; // summary width of all added words
const bool _checkTilde = false; // do we need a special text block for tilde symbol
std::vector<EntityLinkData> _links;
base::flat_map<
const QChar*,
std::vector<StartedEntity>> _startedEntities;
uint16 _maxLnkIndex = 0;
// current state
int32 _flags = 0;
uint16 _lnkIndex = 0;
EmojiPtr _emoji = nullptr; // current emoji, if current word is an emoji, or zero
int32 _blockStart = 0; // offset in result, from which current parsed block is started
int32 _diacs = 0; // diac chars skipped without good char
QFixed _sumWidth;
bool _sumFinished = false;
bool _newlineAwaited = false;
// current char data
QChar _ch; // current char (low surrogate, if current char is surrogate pair)
int32 _emojiLookback = 0; // how far behind the current ptr to look for current emoji
bool _lastSkipped = false; // did we skip current char
};
Parser::StartedEntity::StartedEntity(TextBlockFlags flags) : _value(flags) {
Expects(_value >= 0 && _value < int(kStringLinkIndexShift));
}
Parser::StartedEntity::StartedEntity(uint16 lnkIndex) : _value(lnkIndex) {
Expects(_value >= kStringLinkIndexShift);
}
std::optional<TextBlockFlags> Parser::StartedEntity::flags() const {
if (_value < int(kStringLinkIndexShift)) {
return TextBlockFlags(_value);
}
return std::nullopt;
}
std::optional<uint16> Parser::StartedEntity::lnkIndex() const {
if (_value >= int(kStringLinkIndexShift)) {
return uint16(_value);
}
return std::nullopt;
}
Parser::Parser(
not_null<String*> string,
const QString &text,
const TextParseOptions &options,
const std::any &context)
: Parser(
string,
PrepareRichFromPlain(text, options),
options,
context,
ReadyToken()) {
}
Parser::Parser(
not_null<String*> string,
const TextWithEntities &textWithEntities,
const TextParseOptions &options,
const std::any &context)
: Parser(
string,
PrepareRichFromRich(textWithEntities, options),
options,
context,
ReadyToken()) {
}
Parser::Parser(
not_null<String*> string,
TextWithEntities &&source,
const TextParseOptions &options,
const std::any &context,
ReadyToken)
: _t(string)
, _source(std::move(source))
, _context(context)
, _start(_source.text.constData())
, _end(_start + _source.text.size())
, _ptr(_start)
, _entitiesEnd(_source.entities.end())
, _waitingEntity(_source.entities.begin())
, _rich(options.flags & TextParseRichText)
, _multiline(options.flags & TextParseMultiline)
, _stopAfterWidth(ComputeStopAfter(options, *_t->_st))
, _checkTilde(ComputeCheckTilde(*_t->_st)) {
parse(options);
}
void Parser::blockCreated() {
_sumWidth += _t->_blocks.back()->f_width();
if (_sumWidth.floor().toInt() > _stopAfterWidth) {
_sumFinished = true;
}
}
void Parser::createBlock(int32 skipBack) {
if (_lnkIndex < kStringLinkIndexShift && _lnkIndex > _maxLnkIndex) {
_maxLnkIndex = _lnkIndex;
}
int32 len = int32(_t->_text.size()) + skipBack - _blockStart;
if (len > 0) {
bool newline = !_emoji && (len == 1 && _t->_text.at(_blockStart) == QChar::LineFeed);
if (_newlineAwaited) {
_newlineAwaited = false;
if (!newline) {
_t->_text.insert(_blockStart, QChar::LineFeed);
createBlock(skipBack - len);
}
}
_lastSkipped = false;
if (_emoji) {
_t->_blocks.push_back(Block::Emoji(_t->_st->font, _t->_text, _blockStart, len, _flags, _lnkIndex, _emoji));
_emoji = nullptr;
_lastSkipped = true;
} else if (newline) {
_t->_blocks.push_back(Block::Newline(_t->_st->font, _t->_text, _blockStart, len, _flags, _lnkIndex));
} else {
_t->_blocks.push_back(Block::Text(_t->_st->font, _t->_text, _t->_minResizeWidth, _blockStart, len, _flags, _lnkIndex));
}
_blockStart += len;
blockCreated();
}
}
void Parser::createSkipBlock(int32 w, int32 h) {
createBlock();
_t->_text.push_back('_');
_t->_blocks.push_back(Block::Skip(_t->_st->font, _t->_text, _blockStart++, w, h, _lnkIndex));
blockCreated();
}
void Parser::createNewlineBlock() {
createBlock();
_t->_text.push_back(QChar::LineFeed);
createBlock();
}
bool Parser::checkCommand() {
bool result = false;
for (QChar c = ((_ptr < _end) ? *_ptr : 0); c == TextCommand; c = ((_ptr < _end) ? *_ptr : 0)) {
if (!readCommand()) {
break;
}
result = true;
}
return result;
}
void Parser::finishEntities() {
while (!_startedEntities.empty()
&& (_ptr >= _startedEntities.begin()->first || _ptr >= _end)) {
auto list = std::move(_startedEntities.begin()->second);
_startedEntities.erase(_startedEntities.begin());
while (!list.empty()) {
if (const auto flags = list.back().flags()) {
if (_flags & (*flags)) {
createBlock();
_flags &= ~(*flags);
if (((*flags) & TextBlockFPre)
&& !_t->_blocks.empty()
&& _t->_blocks.back()->type() != TextBlockTNewline) {
_newlineAwaited = true;
}
}
} else if (const auto lnkIndex = list.back().lnkIndex()) {
if (_lnkIndex == *lnkIndex) {
createBlock();
_lnkIndex = 0;
}
}
list.pop_back();
}
}
}
// Returns true if at least one entity was parsed in the current position.
bool Parser::checkEntities() {
finishEntities();
skipPassedEntities();
if (_waitingEntity == _entitiesEnd
|| _ptr < _start + _waitingEntity->offset()) {
return false;
}
auto flags = TextBlockFlags();
auto link = EntityLinkData();
const auto entityType = _waitingEntity->type();
const auto entityLength = _waitingEntity->length();
const auto entityBegin = _start + _waitingEntity->offset();
const auto entityEnd = entityBegin + entityLength;
if (entityType == EntityType::Bold) {
flags = TextBlockFBold;
} else if (entityType == EntityType::Semibold) {
flags = TextBlockFSemibold;
} else if (entityType == EntityType::Italic) {
flags = TextBlockFItalic;
} else if (entityType == EntityType::Underline) {
flags = TextBlockFUnderline;
} else if (entityType == EntityType::StrikeOut) {
flags = TextBlockFStrikeOut;
} else if (entityType == EntityType::Code) { // #TODO entities
flags = TextBlockFCode;
} else if (entityType == EntityType::Pre) {
flags = TextBlockFPre;
createBlock();
if (!_t->_blocks.empty() && _t->_blocks.back()->type() != TextBlockTNewline) {
createNewlineBlock();
}
} else if (entityType == EntityType::Url
|| entityType == EntityType::Email
|| entityType == EntityType::Mention
|| entityType == EntityType::Hashtag
|| entityType == EntityType::Cashtag
|| entityType == EntityType::BotCommand) {
link.type = entityType;
link.data = QString(entityBegin, entityLength);
if (link.type == EntityType::Url) {
computeLinkText(link.data, &link.text, &link.shown);
} else {
link.text = link.data;
}
} else if (entityType == EntityType::CustomUrl
|| entityType == EntityType::MentionName) {
link.type = entityType;
link.data = _waitingEntity->data();
link.text = QString(_start + _waitingEntity->offset(), _waitingEntity->length());
}
if (link.type != EntityType::Invalid) {
createBlock();
_links.push_back(link);
_lnkIndex = kStringLinkIndexShift + _links.size();
_startedEntities[entityEnd].emplace_back(_lnkIndex);
} else if (flags) {
if (!(_flags & flags)) {
createBlock();
_flags |= flags;
_startedEntities[entityEnd].emplace_back(flags);
}
}
++_waitingEntity;
skipBadEntities();
return true;
}
void Parser::skipPassedEntities() {
while (_waitingEntity != _entitiesEnd
&& _start + _waitingEntity->offset() + _waitingEntity->length() <= _ptr) {
++_waitingEntity;
}
}
void Parser::skipBadEntities() {
if (_links.size() >= 0x7FFF) {
while (_waitingEntity != _entitiesEnd
&& (isLinkEntity(*_waitingEntity)
|| isInvalidEntity(*_waitingEntity))) {
++_waitingEntity;
}
} else {
while (_waitingEntity != _entitiesEnd && isInvalidEntity(*_waitingEntity)) {
++_waitingEntity;
}
}
}
bool Parser::readSkipBlockCommand() {
const QChar *afterCmd = textSkipCommand(_ptr, _end, _links.size() < 0x7FFF);
if (afterCmd == _ptr) {
return false;
}
ushort cmd = (++_ptr)->unicode();
++_ptr;
switch (cmd) {
case TextCommandSkipBlock:
createSkipBlock(_ptr->unicode(), (_ptr + 1)->unicode());
break;
}
_ptr = afterCmd;
return true;
}
bool Parser::readCommand() {
const QChar *afterCmd = textSkipCommand(_ptr, _end, _links.size() < 0x7FFF);
if (afterCmd == _ptr) {
return false;
}
ushort cmd = (++_ptr)->unicode();
++_ptr;
switch (cmd) {
case TextCommandBold:
if (!(_flags & TextBlockFBold)) {
createBlock();
_flags |= TextBlockFBold;
}
break;
case TextCommandNoBold:
if (_flags & TextBlockFBold) {
createBlock();
_flags &= ~TextBlockFBold;
}
break;
case TextCommandSemibold:
if (!(_flags & TextBlockFSemibold)) {
createBlock();
_flags |= TextBlockFSemibold;
}
break;
case TextCommandNoSemibold:
if (_flags & TextBlockFSemibold) {
createBlock();
_flags &= ~TextBlockFSemibold;
}
break;
case TextCommandItalic:
if (!(_flags & TextBlockFItalic)) {
createBlock();
_flags |= TextBlockFItalic;
}
break;
case TextCommandNoItalic:
if (_flags & TextBlockFItalic) {
createBlock();
_flags &= ~TextBlockFItalic;
}
break;
case TextCommandUnderline:
if (!(_flags & TextBlockFUnderline)) {
createBlock();
_flags |= TextBlockFUnderline;
}
break;
case TextCommandNoUnderline:
if (_flags & TextBlockFUnderline) {
createBlock();
_flags &= ~TextBlockFUnderline;
}
break;
case TextCommandStrikeOut:
if (!(_flags & TextBlockFStrikeOut)) {
createBlock();
_flags |= TextBlockFStrikeOut;
}
break;
case TextCommandNoStrikeOut:
if (_flags & TextBlockFStrikeOut) {
createBlock();
_flags &= ~TextBlockFStrikeOut;
}
break;
case TextCommandLinkIndex:
if (_ptr->unicode() != _lnkIndex) {
createBlock();
_lnkIndex = _ptr->unicode();
}
break;
case TextCommandLinkText: {
createBlock();
int32 len = _ptr->unicode();
_links.push_back(EntityLinkData{
.data = QString(++_ptr, len),
.type = EntityType::CustomUrl
});
_lnkIndex = kStringLinkIndexShift + _links.size();
} break;
case TextCommandSkipBlock:
createSkipBlock(_ptr->unicode(), (_ptr + 1)->unicode());
break;
}
_ptr = afterCmd;
return true;
}
void Parser::parseCurrentChar() {
_ch = ((_ptr < _end) ? *_ptr : 0);
_emojiLookback = 0;
const auto isNewLine = _multiline && IsNewline(_ch);
const auto isSpace = IsSpace(_ch) && _ch != QChar(160);
const auto isDiac = IsDiac(_ch);
const auto isTilde = _checkTilde && (_ch == '~');
const auto skip = [&] {
if (IsBad(_ch) || _ch.isLowSurrogate()) {
return true;
} else if (_ch == 0xFE0F && Platform::IsMac()) {
// Some sequences like 0x0E53 0xFE0F crash OS X harfbuzz text processing :(
return true;
} else if (isDiac) {
if (_lastSkipped || _emoji || ++_diacs > kMaxDiacAfterSymbol) {
return true;
}
} else if (_ch.isHighSurrogate()) {
if (_ptr + 1 >= _end || !(_ptr + 1)->isLowSurrogate()) {
return true;
}
const auto ucs4 = QChar::surrogateToUcs4(_ch, *(_ptr + 1));
if (ucs4 >= 0xE0000) {
// Unicode tags are skipped.
// Only place they work is in some flag emoji,
// but in that case they were already parsed as emoji before.
//
// For unknown reason in some unknown cases strings with such
// symbols lead to crashes on some Linux distributions, see
// https://github.com/telegramdesktop/tdesktop/issues/7005
//
// At least one crashing text was starting that way:
//
// 0xd83d 0xdcda 0xdb40 0xdc69 0xdb40 0xdc64 0xdb40 0xdc6a
// 0xdb40 0xdc77 0xdb40 0xdc7f 0x32 ... simple text here ...
//
// or in codepoints:
//
// 0x1f4da 0xe0069 0xe0064 0xe006a 0xe0077 0xe007f 0x32 ...
return true;
}
}
return false;
}();
if (_ch.isHighSurrogate() && !skip) {
_t->_text.push_back(_ch);
++_ptr;
_ch = *_ptr;
_emojiLookback = 1;
}
_lastSkipped = skip;
if (skip) {
_ch = 0;
} else {
if (isTilde) { // tilde fix in OpenSans
if (!(_flags & TextBlockFTilde)) {
createBlock(-_emojiLookback);
_flags |= TextBlockFTilde;
}
} else {
if (_flags & TextBlockFTilde) {
createBlock(-_emojiLookback);
_flags &= ~TextBlockFTilde;
}
}
if (isNewLine) {
createNewlineBlock();
} else if (isSpace) {
_t->_text.push_back(QChar::Space);
} else {
if (_emoji) {
createBlock(-_emojiLookback);
}
_t->_text.push_back(_ch);
}
if (!isDiac) _diacs = 0;
}
}
void Parser::parseEmojiFromCurrent() {
int len = 0;
auto e = Emoji::Find(_ptr - _emojiLookback, _end, &len);
if (!e) return;
for (int l = len - _emojiLookback - 1; l > 0; --l) {
_t->_text.push_back(*++_ptr);
}
if (e->hasPostfix()) {
Assert(!_t->_text.isEmpty());
const auto last = _t->_text[_t->_text.size() - 1];
if (last.unicode() != Emoji::kPostfix) {
_t->_text.push_back(QChar(Emoji::kPostfix));
++len;
}
}
createBlock(-len);
_emoji = e;
}
bool Parser::isInvalidEntity(const EntityInText &entity) const {
const auto length = entity.length();
return (_start + entity.offset() + length > _end) || (length <= 0);
}
bool Parser::isLinkEntity(const EntityInText &entity) const {
const auto type = entity.type();
const auto urls = {
EntityType::Url,
EntityType::CustomUrl,
EntityType::Email,
EntityType::Hashtag,
EntityType::Cashtag,
EntityType::Mention,
EntityType::MentionName,
EntityType::BotCommand
};
return ranges::find(urls, type) != std::end(urls);
}
void Parser::parse(const TextParseOptions &options) {
skipBadEntities();
trimSourceRange();
_t->_text.resize(0);
_t->_text.reserve(_end - _ptr);
for (; _ptr <= _end; ++_ptr) {
while (checkEntities() || (_rich && checkCommand())) {
}
parseCurrentChar();
parseEmojiFromCurrent();
if (_sumFinished || _t->_text.size() >= 0x8000) {
break; // 32k max
}
}
createBlock();
checkForElidedSkipBlock();
finalize(options);
}
void Parser::trimSourceRange() {
const auto firstMonospaceOffset = EntityInText::FirstMonospaceOffset(
_source.entities,
_end - _start);
while (_ptr != _end && IsTrimmed(*_ptr, _rich) && _ptr != _start + firstMonospaceOffset) {
++_ptr;
}
while (_ptr != _end && IsTrimmed(*(_end - 1), _rich)) {
--_end;
}
}
void Parser::checkForElidedSkipBlock() {
if (!_sumFinished || !_rich) {
return;
}
// We could've skipped the final skip block command.
for (; _ptr < _end; ++_ptr) {
if (*_ptr == TextCommand && readSkipBlockCommand()) {
break;
}
}
}
void Parser::finalize(const TextParseOptions &options) {
_t->_links.resize(_maxLnkIndex);
for (auto &block : _t->_blocks) {
const auto shiftedIndex = block->lnkIndex();
if (shiftedIndex <= kStringLinkIndexShift) {
continue;
}
const auto realIndex = (shiftedIndex - kStringLinkIndexShift);
const auto index = _maxLnkIndex + realIndex;
block->setLnkIndex(index);
if (_t->_links.size() >= index) {
continue;
}
_t->_links.resize(index);
const auto handler = Integration::Instance().createLinkHandler(
_links[realIndex - 1],
_context);
if (handler) {
_t->setLink(index, handler);
}
}
_t->_links.squeeze();
_t->_blocks.squeeze();
_t->_text.squeeze();
}
void Parser::computeLinkText(
const QString &linkData,
QString *outLinkText,
EntityLinkShown *outShown) {
auto url = QUrl(linkData);
auto good = QUrl(url.isValid()
? url.toEncoded()
: QByteArray());
auto readable = good.isValid()
? good.toDisplayString()
: linkData;
*outLinkText = _t->_st->font->elided(readable, st::linkCropLimit);
*outShown = (*outLinkText == readable)
? EntityLinkShown::Full
: EntityLinkShown::Partial;
}
namespace {
// COPIED FROM qtextengine.cpp AND MODIFIED
struct BidiStatus {
BidiStatus() {
eor = QChar::DirON;
lastStrong = QChar::DirON;
last = QChar:: DirON;
dir = QChar::DirON;
}
QChar::Direction eor;
QChar::Direction lastStrong;
QChar::Direction last;
QChar::Direction dir;
};
enum { _MaxBidiLevel = 61 };
enum { _MaxItemLength = 4096 };
struct BidiControl {
inline BidiControl(bool rtl)
: base(rtl ? 1 : 0), level(rtl ? 1 : 0) {}
inline void embed(bool rtl, bool o = false) {
unsigned int toAdd = 1;
if((level%2 != 0) == rtl ) {
++toAdd;
}
if (level + toAdd <= _MaxBidiLevel) {
ctx[cCtx].level = level;
ctx[cCtx].override = override;
cCtx++;
override = o;
level += toAdd;
}
}
inline bool canPop() const { return cCtx != 0; }
inline void pdf() {
Q_ASSERT(cCtx);
--cCtx;
level = ctx[cCtx].level;
override = ctx[cCtx].override;
}
inline QChar::Direction basicDirection() const {