forked from geode-sdk/geode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMDTextArea.cpp
More file actions
879 lines (777 loc) · 32 KB
/
MDTextArea.cpp
File metadata and controls
879 lines (777 loc) · 32 KB
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
#include <Geode/binding/ProfilePage.hpp>
#include <Geode/binding/LevelTools.hpp>
#include <Geode/binding/LevelInfoLayer.hpp>
#include <Geode/binding/CCContentLayer.hpp>
#include <Geode/binding/GJSearchObject.hpp>
#include <Geode/binding/LevelBrowserLayer.hpp>
#include <Geode/loader/Mod.hpp>
#include <Geode/loader/Loader.hpp>
#include <Geode/ui/MDTextArea.hpp>
#include <Geode/ui/BreakLine.hpp>
#include <Geode/ui/NineSlice.hpp>
#include <Geode/utils/casts.hpp>
#include <Geode/utils/cocos.hpp>
#include <Geode/utils/web.hpp>
#include <Geode/utils/ranges.hpp>
#include <Geode/utils/string.hpp>
#include <ui/mods/list/ModItem.hpp>
#include <md4c.h>
#include <charconv>
#include <Geode/loader/Log.hpp>
#include <Geode/ui/GeodeUI.hpp>
#include <memory>
#include <server/Server.hpp>
#include <regex>
using namespace geode::prelude;
static constexpr float g_fontScale = .5f;
static constexpr float g_paragraphPadding = 7.f;
static constexpr float g_indent = 7.f;
static constexpr float g_codeBlockIndent = 8.f;
static constexpr ccColor3B g_linkColor = {0x7f, 0xf4, 0xf4};
class MDTextArea::Impl {
public:
std::string m_text;
cocos2d::CCSize m_size;
NineSlice* m_bgSprite = nullptr;
cocos2d::CCMenu* m_content = nullptr;
CCScrollLayerExt* m_scrollLayer = nullptr;
TextRenderer* m_renderer = nullptr;
bool m_compatibilityMode = false;
};
MDTextArea::MDTextArea() : m_impl(std::make_unique<Impl>()) {}
auto makeMdFont() -> TextRenderer::Font {
return [](int style) -> TextRenderer::Label {
if ((style & TextStyleBold) && (style & TextStyleItalic)) {
return CCLabelBMFont::create("", "mdFontBI.fnt"_spr);
}
if ((style & TextStyleBold)) {
return CCLabelBMFont::create("", "mdFontB.fnt"_spr);
}
if ((style & TextStyleItalic)) {
return CCLabelBMFont::create("", "mdFontI.fnt"_spr);
}
return CCLabelBMFont::create("", "mdFont.fnt"_spr);
};
}
auto makeMdMonoFont() -> TextRenderer::Font {
return [](int style) -> TextRenderer::Label {
return CCLabelBMFont::create("", "mdFontMono.fnt"_spr);
};
}
class MDContentLayer : public CCContentLayer {
protected:
CCMenu* m_content;
public:
static MDContentLayer* create(CCMenu* content, float width, float height) {
auto ret = new MDContentLayer();
if (ret->initWithColor({ 0, 255, 0, 0 }, width, height)) {
ret->m_content = content;
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
void setPosition(CCPoint const& pos) override {
// cringe CCContentLayer expect its children to
// all be TableViewCells
CCLayerColor::setPosition(pos);
// so that's why based MDContentLayer expects itself
// to have a CCMenu :-)
if (m_content) {
for (auto child : CCArrayExt<CCNode*>(m_content->getChildren())) {
auto y = this->getPositionY() + child->getPositionY();
child->setVisible(
!((m_content->getContentSize().height < y) ||
(y < -child->getContentSize().height))
);
}
}
}
};
Result<ccColor3B> colorForIdentifier(std::string tag) {
auto sv = std::string_view(tag);
if (tag.length() > 2 && tag[1] == '-') {
return cc3bFromHexString(sv.substr(2));
}
// Support the old form of <carbitaryletters hex>
else if (tag.find(' ') != std::string::npos) {
return cc3bFromHexString(string::trim(tag.substr(tag.find(' ') + 1)));
}
else {
auto colorText = sv.substr(1);
if (!colorText.size()) {
return Err("No color specified");
}
else if (colorText.size() > 1) {
return Err("Color tag " + tag + " unexpectedly long, either do <cx> or <c hex>");
}
else {
switch (colorText.front()) {
case 'a': return Ok(ccc3(150, 50, 255)); break;
case 'b': return Ok(ccc3(74, 82, 225)); break;
case 'c': return Ok(ccc3(255, 255, 150)); break;
case 'd': return Ok(ccc3(255, 150, 255)); break;
case 'f': return Ok(ccc3(150, 255, 255)); break;
case 'g': return Ok(ccc3(64, 227, 72)); break;
case 'j': return Ok(ccc3(50, 200, 255)); break;
case 'l': return Ok(ccc3(96, 171, 239)); break;
case 'o': return Ok(ccc3(255, 165, 75)); break;
case 'p': return Ok(ccc3(255, 0, 255)); break;
case 'r': return Ok(ccc3(255, 90, 90)); break;
case 's': return Ok(ccc3(255, 220, 65)); break;
case 'y': return Ok(ccc3(255, 255, 0)); break;
default: return Err("Unknown color {}", colorText);
}
}
}
return Err("Unknown error");
}
bool MDTextArea::init(std::string str, CCSize const& size) {
if (!CCLayer::init()) return false;
this->ignoreAnchorPointForPosition(false);
this->setAnchorPoint({ .5f, .5f });
m_impl->m_text = std::move(str);
m_impl->m_size = size - CCSize { 15.f, 0.f };
this->setContentSize(m_impl->m_size);
m_impl->m_renderer = TextRenderer::create();
CC_SAFE_RETAIN(m_impl->m_renderer);
m_impl->m_bgSprite = NineSlice::create("square02b_001.png", { 0.0f, 0.0f, 80.0f, 80.0f });
m_impl->m_bgSprite->setScale(.5f);
m_impl->m_bgSprite->setColor({ 0, 0, 0 });
m_impl->m_bgSprite->setOpacity(75);
m_impl->m_bgSprite->setContentSize(size * 2);
m_impl->m_bgSprite->setPosition(m_impl->m_size / 2);
this->addChild(m_impl->m_bgSprite);
m_impl->m_scrollLayer = ScrollLayer::create({ 0, 0, m_impl->m_size.width, m_impl->m_size.height }, true);
m_impl->m_content = CCMenu::create();
m_impl->m_content->setZOrder(2);
auto content = MDContentLayer::create(m_impl->m_content, m_impl->m_size.width, m_impl->m_size.height);
m_impl->m_scrollLayer->m_contentLayer = content;
m_impl->m_scrollLayer->addChild(content);
content->addChild(m_impl->m_content);
m_impl->m_scrollLayer->setTouchEnabled(true);
this->addChild(m_impl->m_scrollLayer);
this->updateLabel();
return true;
}
MDTextArea::~MDTextArea() {
CC_SAFE_RELEASE(m_impl->m_renderer);
}
void MDTextArea::onLink(CCObject* pSender) {
auto href = static_cast<CCString*>(static_cast<CCNode*>(pSender)->getUserObject());
auto layer = FLAlertLayer::create(
this, "Hold Up!",
fmt::format("Links are spooky! Are you sure you want to go to <cy>{}</c>?", href->getCString()),
"Cancel", "Yes", 360.f
);
layer->setUserObject(href);
layer->show();
}
void MDTextArea::onGDProfile(CCObject* pSender) {
auto href = static_cast<CCString*>(static_cast<CCNode*>(pSender)->getUserObject());
auto profile = std::string(href->getCString());
profile = profile.substr(profile.find(":") + 1);
auto res = numFromString<int>(profile);
if (res.isErr()) {
FLAlertLayer::create(
"Error",
"Invalid profile ID: <cr>" + profile +
"</c>. This is "
"probably the mod developer's fault, report the bug to them.",
"OK"
)->show();
return;
}
ProfilePage::create(res.unwrap(), false)->show();
}
void MDTextArea::onGDLevel(CCObject* pSender) {
auto href = static_cast<CCString*>(static_cast<CCNode*>(pSender)->getUserObject());
auto level = std::string(href->getCString());
level = level.substr(level.find(":") + 1);
auto res = numFromString<int>(level);
if (res.isErr()) {
FLAlertLayer::create(
"Error",
"Invalid level ID: <cr>" + level +
"</c>. This is "
"probably the mod developers's fault, report the bug to them.",
"OK"
)->show();
return;
}
auto searchObject = GJSearchObject::create(SearchType::Type19, fmt::format("{}&gameVersion=22", res.unwrap()));
auto scene = LevelBrowserLayer::scene(searchObject);
CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.5f, scene));
}
void MDTextArea::onGeodeMod(CCObject* sender) {
auto href = static_cast<CCString*>(static_cast<CCNode*>(sender)->getUserObject());
std::string_view modID = href->getCString();
modID.remove_prefix(modID.find(':') + 1);
(void)openInfoPopup(std::string{modID});
}
void MDTextArea::FLAlert_Clicked(FLAlertLayer* layer, bool btn) {
if (btn) {
web::openLinkInBrowser(static_cast<CCString*>(layer->getUserObject())->getCString());
}
}
struct MDParser {
static std::string s_lastLink;
static bool s_lastLinkWasAuto;
static std::string s_lastImage;
static bool s_isOrderedList;
static bool s_isCodeBlock;
static float s_codeStart;
static size_t s_orderedListNum;
static std::vector<TextRenderer::Label> s_codeSpans;
static bool s_breakListLine;
static int parseText(MD_TEXTTYPE type, MD_CHAR const* rawText, MD_SIZE size, void* mdtextarea) {
auto textarea = static_cast<MDTextArea*>(mdtextarea);
auto renderer = textarea->m_impl->m_renderer;
auto compatibilityMode = textarea->m_impl->m_compatibilityMode;
auto text = std::string(rawText, size);
switch (type) {
case MD_TEXTTYPE::MD_TEXT_CODE:
{
auto rendered = renderer->renderString(text);
if (!s_isCodeBlock) {
// code span BGs need to be rendered after all
// rendering is done since the position of the
// rendered labels may change after alignments
// are adjusted
ranges::push(s_codeSpans, rendered);
}
}
break;
case MD_TEXTTYPE::MD_TEXT_BR:
{
renderer->breakLine();
}
break;
case MD_TEXTTYPE::MD_TEXT_SOFTBR:
{
renderer->renderString(" ");
}
break;
case MD_TEXTTYPE::MD_TEXT_NORMAL:
{
if (!s_lastLink.empty()) {
// Render `<mod:mod.id>` as a `ModItem`
if (s_lastLinkWasAuto && s_lastLink.starts_with("mod:")) {
auto item = AnyModItem::create(s_lastLink.substr(s_lastLink.find(':') + 1));
item->updateDisplay(textarea->m_impl->m_size.width, ModListDisplay::SmallList);
renderer->renderNode(item);
}
else {
renderer->pushDecoFlags(TextDecorationUnderline); // force underline for links
auto rendered = renderer->renderStringInteractive(
text, textarea,
utils::string::startsWith(s_lastLink, "user:")
? menu_selector(MDTextArea::onGDProfile)
: utils::string::startsWith(s_lastLink, "level:")
? menu_selector(MDTextArea::onGDLevel)
: utils::string::startsWith(s_lastLink, "mod:")
? menu_selector(MDTextArea::onGeodeMod)
: menu_selector(MDTextArea::onLink)
);
for (auto const& label : rendered) {
label.m_node->setUserObject(CCString::create(s_lastLink));
}
renderer->popDecoFlags();
}
}
else if (!s_lastImage.empty()) {
bool isFrame = false;
const auto splitOnce = [](const std::string& str, char delim) -> std::pair<std::string, std::string> {
const auto pos = str.find(delim);
if (pos == std::string::npos) {
return { str, {} };
}
return { str.substr(0, pos), str.substr(pos + 1) };
};
// key value pair of arguments
std::vector<std::pair<std::string, std::string>> imgArguments;
auto split = splitOnce(s_lastImage, '?');
s_lastImage = split.first;
imgArguments = ranges::map<decltype(imgArguments)>(utils::string::split(split.second, "&"), [&](auto str) {
return splitOnce(str, '=');
});
float spriteScale = 1.0f;
float spriteWidth = 0.0f;
float spriteHeight = 0.0f;
for (auto [key, value] : imgArguments) {
if (key == "scale") {
auto scaleRes = utils::numFromString<float>(value);
if (scaleRes) {
spriteScale = scaleRes.unwrap();
}
}
else if (key == "width") {
auto widthRes = utils::numFromString<float>(value);
if (widthRes) {
spriteWidth = widthRes.unwrap();
}
}
else if (key == "height") {
auto heightRes = utils::numFromString<float>(value);
if (heightRes) {
spriteHeight = heightRes.unwrap();
}
}
}
if (utils::string::startsWith(s_lastImage, "frame:")) {
s_lastImage = s_lastImage.substr(s_lastImage.find(":") + 1);
isFrame = true;
}
CCSprite* spr = nullptr;
if (isFrame) {
spr = CCSprite::createWithSpriteFrameName(s_lastImage.c_str());
}
else {
spr = CCSprite::create(s_lastImage.c_str());
}
if (spr && !spr->isUsingFallback()) {
spr->setScale(spriteScale);
if (spriteWidth > 0.0f && spriteHeight <= 0.0f) {
limitNodeWidth(spr, spriteWidth, 999.f, .1f);
}
else if (spriteHeight > 0.0f && spriteWidth <= 0.0f) {
limitNodeHeight(spr, spriteHeight, 999.f, .1f);
}
else if (spriteWidth > 0.0f && spriteHeight > 0.0f) {
limitNodeSize(spr, { spriteWidth, spriteHeight }, 999.f, .1f);
}
renderer->renderNode(spr);
}
else {
renderer->renderString(text);
}
s_lastImage = "";
}
else {
renderer->renderString(text);
}
}
break;
case MD_TEXTTYPE::MD_TEXT_HTML:
{
if (text.size() > 2) {
auto tag = utils::string::trim(text.substr(1, text.size() - 2));
auto isClosing = tag.front() == '/';
if (isClosing) tag.erase(tag.begin());
if (tag.front() != 'c') {
log::warn("Unknown tag {}", text);
renderer->renderString(text);
}
else {
if (isClosing) {
renderer->popColor();
}
else {
auto color = colorForIdentifier(std::move(tag));
if (color) {
renderer->pushColor(color.unwrap());
}
else if (compatibilityMode) {
renderer->pushColor(ccc3(255, 0, 0));
}
else {
log::warn("Error parsing color: {}", color.unwrapErr());
}
}
}
}
else {
log::warn("Too short tag {}", text);
renderer->renderString(text);
}
}
break;
default:
{
log::warn("Unhandled text type {}", static_cast<int>(type));
}
break;
}
return 0;
}
static int enterBlock(MD_BLOCKTYPE type, void* detail, void* mdtextarea) {
auto textarea = static_cast<MDTextArea*>(mdtextarea);
auto renderer = textarea->m_impl->m_renderer;
switch (type) {
case MD_BLOCKTYPE::MD_BLOCK_DOC:
{
}
break;
case MD_BLOCKTYPE::MD_BLOCK_H:
{
auto hdetail = static_cast<MD_BLOCK_H_DETAIL*>(detail);
renderer->pushStyleFlags(TextStyleBold);
switch (hdetail->level) {
case 1: renderer->pushScale(g_fontScale * 2.f); break;
case 2: renderer->pushScale(g_fontScale * 1.5f); break;
case 3: renderer->pushScale(g_fontScale * 1.17f); break;
case 4: renderer->pushScale(g_fontScale); break;
case 5: renderer->pushScale(g_fontScale * .83f); break;
default:
case 6: renderer->pushScale(g_fontScale * .67f); break;
}
// switch (hdetail->level) {
// case 3: renderer->pushCaps(TextCapitalization::AllUpper); break;
// }
}
break;
case MD_BLOCKTYPE::MD_BLOCK_P:
{
}
break;
case MD_BLOCKTYPE::MD_BLOCK_UL:
case MD_BLOCKTYPE::MD_BLOCK_OL:
{
renderer->pushIndent(g_indent);
s_isOrderedList = type == MD_BLOCKTYPE::MD_BLOCK_OL;
s_orderedListNum = 0;
if (s_breakListLine) {
renderer->breakLine();
s_breakListLine = false;
}
}
break;
case MD_BLOCKTYPE::MD_BLOCK_HR:
{
renderer->breakLine(g_paragraphPadding / 2);
renderer->renderNode(BreakLine::create(textarea->m_impl->m_size.width));
renderer->breakLine(g_paragraphPadding);
}
break;
case MD_BLOCKTYPE::MD_BLOCK_LI:
{
if (s_breakListLine) {
renderer->breakLine();
s_breakListLine = false;
}
auto cursor = renderer->getCursorPos();
auto indent = renderer->getCurrentIndent();
renderer->moveCursor({ indent, cursor.y });
renderer->pushOpacity(renderer->getCurrentOpacity() / 2);
auto lidetail = static_cast<MD_BLOCK_LI_DETAIL*>(detail);
if (s_isOrderedList) {
s_orderedListNum++;
renderer->renderString(std::to_string(s_orderedListNum) + ". ");
}
else {
renderer->renderString("• ");
}
renderer->popOpacity();
auto markerWidth = renderer->getCursorPos().x - indent;
renderer->pushIndent(markerWidth);
s_breakListLine = true;
}
break;
case MD_BLOCKTYPE::MD_BLOCK_CODE:
{
s_isCodeBlock = true;
s_codeStart = renderer->getCursorPos().y;
renderer->pushFont(makeMdMonoFont());
renderer->pushIndent(g_codeBlockIndent);
renderer->pushWrapOffset(g_codeBlockIndent);
}
break;
default:
{
log::warn("Unhandled block enter type {}", static_cast<int>(type));
}
break;
}
return 0;
}
static int leaveBlock(MD_BLOCKTYPE type, void* detail, void* mdtextarea) {
auto textarea = static_cast<MDTextArea*>(mdtextarea);
auto renderer = textarea->m_impl->m_renderer;
switch (type) {
case MD_BLOCKTYPE::MD_BLOCK_DOC:
{
}
break;
case MD_BLOCKTYPE::MD_BLOCK_H:
{
auto hdetail = static_cast<MD_BLOCK_H_DETAIL*>(detail);
renderer->breakLine();
if (hdetail->level == 1) {
renderer->breakLine(g_paragraphPadding / 2);
renderer->renderNode(BreakLine::create(textarea->m_impl->m_size.width));
}
renderer->breakLine(g_paragraphPadding);
renderer->popScale();
renderer->popStyleFlags();
// switch (hdetail->level) {
// case 3: renderer->popCaps(); break;
// }
}
break;
case MD_BLOCKTYPE::MD_BLOCK_P:
{
renderer->breakLine();
renderer->breakLine(g_paragraphPadding);
}
break;
case MD_BLOCKTYPE::MD_BLOCK_OL:
case MD_BLOCKTYPE::MD_BLOCK_UL:
{
renderer->popIndent();
if (s_breakListLine) {
renderer->breakLine();
s_breakListLine = false;
}
if (renderer->getCurrentIndent() == 0) {
renderer->breakLine();
}
}
break;
case MD_BLOCKTYPE::MD_BLOCK_CODE:
{
auto codeEnd = renderer->getCursorPos().y;
auto pad = g_codeBlockIndent / 1.5f;
CCSize size { textarea->m_impl->m_size.width - renderer->getCurrentIndent() -
renderer->getCurrentWrapOffset() + pad * 2,
s_codeStart - codeEnd + pad * 2 };
auto bg =
NineSlice::create("square02b_001.png", { 0.0f, 0.0f, 80.0f, 80.0f });
bg->setScale(.25f);
bg->setColor({ 0, 0, 0 });
bg->setOpacity(75);
bg->setContentSize(size * 4);
bg->setPosition(
size.width / 2 + renderer->getCurrentIndent() - pad,
// mmm i love magic numbers
// the -2.f is to offset the the box
// to fit the Ubuntu font very neatly.
// idk if it works the same for other
// fonts
s_codeStart - 2.f + pad - size.height / 2
);
bg->setAnchorPoint({ .5f, .5f });
bg->setZOrder(-1);
textarea->m_impl->m_content->addChild(bg);
renderer->popWrapOffset();
renderer->popIndent();
renderer->popFont();
renderer->breakLine();
}
break;
case MD_BLOCKTYPE::MD_BLOCK_LI:
{
renderer->popIndent();
}
break;
case MD_BLOCKTYPE::MD_BLOCK_HR:
{
}
break;
default:
{
log::warn("Unhandled block leave type {}", static_cast<int>(type));
}
break;
}
return 0;
}
static int enterSpan(MD_SPANTYPE type, void* detail, void* mdtextarea) {
auto renderer = static_cast<MDTextArea*>(mdtextarea)->m_impl->m_renderer;
switch (type) {
case MD_SPANTYPE::MD_SPAN_STRONG:
{
renderer->pushStyleFlags(TextStyleBold);
}
break;
case MD_SPANTYPE::MD_SPAN_EM:
{
renderer->pushStyleFlags(TextStyleItalic);
}
break;
case MD_SPANTYPE::MD_SPAN_DEL:
{
renderer->pushDecoFlags(TextDecorationStrikethrough);
}
break;
case MD_SPANTYPE::MD_SPAN_U:
{
renderer->pushDecoFlags(TextDecorationUnderline);
}
break;
case MD_SPANTYPE::MD_SPAN_IMG:
{
auto adetail = static_cast<MD_SPAN_IMG_DETAIL*>(detail);
s_lastImage = std::string(adetail->src.text, adetail->src.size);
}
break;
case MD_SPANTYPE::MD_SPAN_A:
{
auto adetail = static_cast<MD_SPAN_A_DETAIL*>(detail);
s_lastLink = std::string(adetail->href.text, adetail->href.size);
s_lastLinkWasAuto = adetail->is_autolink != 0;
renderer->pushColor(g_linkColor);
}
break;
case MD_SPANTYPE::MD_SPAN_CODE:
{
s_isCodeBlock = false;
renderer->pushFont(makeMdMonoFont());
}
break;
default:
{
log::warn("Unhandled span enter type {}", static_cast<int>(type));
}
break;
}
return 0;
}
static int leaveSpan(MD_SPANTYPE type, void* detail, void* mdtextarea) {
auto renderer = static_cast<MDTextArea*>(mdtextarea)->m_impl->m_renderer;
switch (type) {
case MD_SPANTYPE::MD_SPAN_STRONG:
{
renderer->popStyleFlags();
}
break;
case MD_SPANTYPE::MD_SPAN_EM:
{
renderer->popStyleFlags();
}
break;
case MD_SPANTYPE::MD_SPAN_DEL:
{
renderer->popDecoFlags();
}
break;
case MD_SPANTYPE::MD_SPAN_U:
{
renderer->popDecoFlags();
}
break;
case MD_SPANTYPE::MD_SPAN_A:
{
renderer->popColor();
s_lastLink = "";
}
break;
case MD_SPANTYPE::MD_SPAN_IMG:
{
s_lastImage = "";
}
break;
case MD_SPANTYPE::MD_SPAN_CODE:
{
renderer->popFont();
}
break;
default:
{
log::warn("Unhandled span leave type {}", static_cast<int>(type));
}
break;
}
return 0;
}
};
std::string MDParser::s_lastLink = "";
bool MDParser::s_lastLinkWasAuto = false;
std::string MDParser::s_lastImage = "";
bool MDParser::s_isOrderedList = false;
size_t MDParser::s_orderedListNum = 0;
bool MDParser::s_isCodeBlock = false;
float MDParser::s_codeStart = 0;
decltype(MDParser::s_codeSpans) MDParser::s_codeSpans = {};
bool MDParser::s_breakListLine = false;
void MDTextArea::updateLabel() {
m_impl->m_renderer->begin(m_impl->m_content, CCPointZero, m_impl->m_size);
m_impl->m_renderer->pushFont(makeMdFont());
m_impl->m_renderer->pushScale(.5f);
m_impl->m_renderer->pushVerticalAlign(TextAlignment::End);
m_impl->m_renderer->pushHorizontalAlign(TextAlignment::Begin);
MD_PARSER parser;
parser.abi_version = 0;
parser.flags = MD_FLAG_UNDERLINE | MD_FLAG_STRIKETHROUGH | MD_FLAG_PERMISSIVEURLAUTOLINKS |
MD_FLAG_PERMISSIVEWWWAUTOLINKS;
parser.text = &MDParser::parseText;
parser.enter_block = &MDParser::enterBlock;
parser.leave_block = &MDParser::leaveBlock;
parser.enter_span = &MDParser::enterSpan;
parser.leave_span = &MDParser::leaveSpan;
parser.debug_log = nullptr;
parser.syntax = nullptr;
MDParser::s_codeSpans = {};
auto textContent = m_impl->m_text;
if (m_impl->m_compatibilityMode) {
textContent = MDTextArea::translateNewlines(m_impl->m_text);
// ery proofing...
utils::string::replaceIP(textContent, "<c_>", "<c->");
}
if (md_parse(textContent.c_str(), textContent.size(), &parser, this)) {
m_impl->m_renderer->renderString("Error parsing Markdown");
}
for (auto& render : MDParser::s_codeSpans) {
auto bg = NineSlice::create("square02b_001.png", { 0.0f, 0.0f, 80.0f, 80.0f });
bg->setScale(.125f);
bg->setColor({ 0, 0, 0 });
bg->setOpacity(75);
bg->setContentSize(render.m_node->getScaledContentSize() * 8 + CCSize { 20.f, .0f });
bg->setPosition(
render.m_node->getPositionX() - 2.5f * (.5f - render.m_node->getAnchorPoint().x),
render.m_node->getPositionY() - .5f
);
bg->setAnchorPoint(render.m_node->getAnchorPoint());
bg->setZOrder(-1);
m_impl->m_content->addChild(bg);
// i know what you're thinking.
// my brother in christ, what the hell is this?
// where did this magical + 1.5f come from?
// the reason is that if you remove them, code
// spans are slightly offset and it triggers my
// OCD.
render.m_node->setPositionY(render.m_node->getPositionY() + 1.5f);
}
m_impl->m_renderer->end();
if (m_impl->m_content->getContentSize().height > m_impl->m_size.height) {
// Generate bottom padding
m_impl->m_scrollLayer->m_contentLayer->setContentSize(m_impl->m_content->getContentSize() + CCSize { 0.f, 12.5 });
m_impl->m_content->setPositionY(10.f);
} else {
m_impl->m_scrollLayer->m_contentLayer->setContentSize(m_impl->m_content->getContentSize());
m_impl->m_content->setPositionY(-2.5f);
}
m_impl->m_scrollLayer->moveToTop();
}
CCScrollLayerExt* MDTextArea::getScrollLayer() const {
return m_impl->m_scrollLayer;
}
void MDTextArea::setString(char const* text) {
m_impl->m_text = text;
this->updateLabel();
}
char const* MDTextArea::getString() {
return m_impl->m_text.c_str();
}
MDTextArea* MDTextArea::create(std::string str, CCSize const& size) {
auto ret = new MDTextArea;
if (ret->init(std::move(str), size)) {
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
MDTextArea* MDTextArea::create(std::string str, CCSize const& size, bool compatibilityMode) {
auto ret = new MDTextArea;
if (ret->init(std::move(str), size)) {
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
std::string MDTextArea::translateNewlines(std::string const& str) {
std::regex newlineRe("(.*\\S)\n(?!\n)");
return std::regex_replace(str, newlineRe, "$1 \n");
}