forked from Kam1k4dze/SubChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathytt_generator.h
639 lines (548 loc) · 21.2 KB
/
ytt_generator.h
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
#pragma once
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <cctype>
#include <optional>
#include <iterator>
#include <queue>
#include <ranges>
#include "utf8.h"
#include "tinyxml2.h"
#include "SimpleIni.h"
#include "magic_enum.hpp"
// Returns the number of UTF‑8 code points in s.
int utf8_length(const std::string &s) {
return static_cast<int>(utf8::distance(s.begin(), s.end()));
}
// Returns the first 'count' UTF‑8 code points of s.
std::string utf8_substr(const std::string &s, int count) {
auto it = s.begin();
int i = 0;
while (it != s.end() && i < count) {
utf8::next(it, s.end());
++i;
}
return {s.begin(), it};
}
// Returns the remainder of s after consuming the first 'count' UTF‑8 code points.
std::string utf8_consume(const std::string &s, int count) {
auto it = s.begin();
int i = 0;
while (it != s.end() && i < count) {
utf8::next(it, s.end());
++i;
}
return {it, s.end()};
}
template<typename T, T Max>
struct Clamped {
T value;
Clamped(T v = 0) : value(clamp(v)) {}
static T clamp(T v) {
return (v > Max) ? Max : v;
}
operator T() const {
return value;
}
Clamped &operator=(T v) {
value = clamp(v);
return *this;
}
};
struct Color {
static const int maxValue = 254;
typedef unsigned char cType;
Clamped<cType, maxValue> r;
Clamped<cType, maxValue> g;
Clamped<cType, maxValue> b;
Clamped<cType, maxValue> a;
static int hexToInt(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return 0;
}
void parseHex(const std::string &hex) {
if (hex.empty()) return;
std::string cleaned = hex;
if (cleaned[0] == '#') {
cleaned = cleaned.substr(1);
}
// Convert to uppercase for consistency
std::transform(cleaned.begin(), cleaned.end(), cleaned.begin(), ::toupper);
// Support formats:
// - #RGB : 3-digit, assume opaque (alpha = maxValue)
// - #RGBA : 4-digit, includes alpha
// - #RRGGBB : 6-digit, assume opaque
// - #RRGGBBAA : 8-digit, includes alpha
if (cleaned.length() == 3) {
r = static_cast<cType>(hexToInt(cleaned[0]) * 16 + hexToInt(cleaned[0]));
g = static_cast<cType>(hexToInt(cleaned[1]) * 16 + hexToInt(cleaned[1]));
b = static_cast<cType>(hexToInt(cleaned[2]) * 16 + hexToInt(cleaned[2]));
a = maxValue;
} else if (cleaned.length() == 4) {
r = static_cast<cType>(hexToInt(cleaned[0]) * 16 + hexToInt(cleaned[0]));
g = static_cast<cType>(hexToInt(cleaned[1]) * 16 + hexToInt(cleaned[1]));
b = static_cast<cType>(hexToInt(cleaned[2]) * 16 + hexToInt(cleaned[2]));
a = static_cast<cType>(hexToInt(cleaned[3]) * 16 + hexToInt(cleaned[3]));
} else if (cleaned.length() == 6) {
r = static_cast<cType>(hexToInt(cleaned[0]) * 16 + hexToInt(cleaned[1]));
g = static_cast<cType>(hexToInt(cleaned[2]) * 16 + hexToInt(cleaned[3]));
b = static_cast<cType>(hexToInt(cleaned[4]) * 16 + hexToInt(cleaned[5]));
a = maxValue;
} else if (cleaned.length() == 8) {
r = static_cast<cType>(hexToInt(cleaned[0]) * 16 + hexToInt(cleaned[1]));
g = static_cast<cType>(hexToInt(cleaned[2]) * 16 + hexToInt(cleaned[3]));
b = static_cast<cType>(hexToInt(cleaned[4]) * 16 + hexToInt(cleaned[5]));
a = static_cast<cType>(hexToInt(cleaned[6]) * 16 + hexToInt(cleaned[7]));
}
}
Color() = default;
Color(cType red, cType green, cType blue, cType alpha = maxValue)
: r(red), g(green), b(blue), a(alpha) {}
Color(const std::string &hexCode) {
parseHex(hexCode);
}
Color(const char *hexCode) {
if (hexCode) parseHex(hexCode);
}
// Convert to hex string (always uppercase with #)
// If alpha is maxValue, the output will be in #RRGGBB format;
// otherwise, it will include alpha as #RRGGBBAA.
std::string toHexString() const {
std::stringstream ss;
ss << '#' << std::uppercase << std::hex << std::setfill('0')
<< std::setw(2) << static_cast<int>(r)
<< std::setw(2) << static_cast<int>(g)
<< std::setw(2) << static_cast<int>(b);
if (a != maxValue) {
ss << std::setw(2) << static_cast<int>(a);
}
return ss.str();
}
operator std::string() const {
return toHexString();
}
bool operator==(const Color &other) const {
return r == other.r && g == other.g && b == other.b && a == other.a;
}
bool operator!=(const Color &other) const {
return !(*this == other);
}
bool operator<(const Color &other) const {
if (r != other.r) return r < other.r;
if (g != other.g) return g < other.g;
if (b != other.b) return b < other.b;
return a < other.a;
}
};
enum class HorizontalAlignment {
Left, Center, Right
};
enum class FontStyle {
Default,
Monospaced, // Courier New
Proportional, // Times New Roman
MonospacedSans, // Lucida Console
ProportionalSans, // Roboto
Casual, // Comic Sans!
Cursive, // Monotype Corsiva
SmallCapitals // (Arial with font-variant: small-caps)
};
enum class EdgeType {
None, HardShadow, Bevel, GlowOutline, SoftShadow
};
enum class TextAlignment {
Left, Right, Center
};
template<typename E>
std::string enumToString(E e) {
auto name = magic_enum::enum_name(e);
return name.empty()
? std::to_string(static_cast<std::underlying_type_t<E>>(e))
: std::string(name);
}
template<typename E>
E enumFromString(const std::string &s) {
if (auto v = magic_enum::enum_cast<E>(s))
return *v;
try {
auto i = std::stoi(s);
return static_cast<E>(i);
} catch (...) {
throw std::invalid_argument(
"Invalid " + std::string(magic_enum::enum_type_name<E>())
+ " value: '" + s + "'");
}
}
template<typename E>
std::string enumToIntString(E e) {
return std::to_string(magic_enum::enum_integer(e));
}
template<typename E>
std::string enumOptionsComment() {
std::string c = ";Options: ";
bool first = true;
for (auto name: magic_enum::enum_names<E>()) {
if (!first) c += ", ";
c += name;
first = false;
}
return c;
}
struct ChatParams {
bool textBold = false;
bool textItalic = false;
bool textUnderline = false;
Color textForegroundColor = {254, 254, 254, 254};
Color textBackgroundColor = {254, 254, 254, 0};
Color textEdgeColor = {0, 0, 0, 254};
EdgeType textEdgeType = EdgeType::SoftShadow;
FontStyle fontStyle = FontStyle::MonospacedSans;
int fontSizePercent = 0;
TextAlignment textAlignment = TextAlignment::Left;
int horizontalMargin = 71;
int verticalMargin = 0;
int verticalSpacing = 4;
int totalDisplayLines = 13;
int maxCharsPerLine = 25;
std::string usernameSeparator = ":";
void saveToFile(const char *filename) const {
CSimpleIniCaseA ini;
ini.SetUnicode();
ini.SetQuotes();
constexpr auto S = "General";
// bools
ini.SetBoolValue(S, "bold", textBold,
";true/false");
ini.SetBoolValue(S, "italic", textItalic,
";true/false");
ini.SetBoolValue(S, "underline", textUnderline,
";true/false");
// colors with format comment
{
auto hf = textForegroundColor.toHexString();
ini.SetValue(S, "textForegroundColor", hf.c_str(),
";Hex color: #RGB, #RGBA, #RRGGBB or #RRGGBBAA");
}
{
auto hb = textBackgroundColor.toHexString();
ini.SetValue(S, "textBackgroundColor", hb.c_str(),
";Hex color: #RGB, #RGBA, #RRGGBB or #RRGGBBAA");
}
{
auto he = textEdgeColor.toHexString();
ini.SetValue(S, "textEdgeColor", he.c_str(),
";Hex color: #RGB, #RGBA, #RRGGBB or #RRGGBBAA");
}
// enums with generated option lists
{
auto val = enumToString(textEdgeType);
auto cm = enumOptionsComment<EdgeType>();
ini.SetValue(S, "textEdgeType", val.c_str(), cm.c_str());
}
{
auto val = enumToString(fontStyle);
auto cm = enumOptionsComment<FontStyle>();
ini.SetValue(S, "fontStyle", val.c_str(), cm.c_str());
}
ini.SetLongValue(S, "fontSizePercent", fontSizePercent,
";0–300 (virtual percent)");
{
auto val = enumToString(textAlignment);
auto cm = enumOptionsComment<TextAlignment>();
ini.SetValue(S, "textAlignment", val.c_str(), cm.c_str());
}
ini.SetLongValue(S, "horizontalMargin", horizontalMargin,
";0–100 (virtual percent)");
ini.SetLongValue(S, "verticalMargin", verticalMargin,
";0-100 (virtual percent)");
ini.SetLongValue(S, "verticalSpacing", verticalSpacing,
";virtual pixels");
ini.SetLongValue(S, "totalDisplayLines", totalDisplayLines,
";lines");
ini.SetLongValue(S, "maxCharsPerLine", maxCharsPerLine,
";characters");
ini.SetValue(S, "usernameSeparator", usernameSeparator.c_str(),
";string between name and message");
ini.SaveFile(filename);
}
bool loadFromFile(const char *filename) {
CSimpleIniCaseA ini;
ini.SetUnicode();
ini.SetQuotes();
if (ini.LoadFile(filename) < 0) return false;
constexpr auto S = "General";
// bools (fallback to existing defaults)
textBold = ini.GetBoolValue(S, "bold", textBold);
textItalic = ini.GetBoolValue(S, "italic", textItalic);
textUnderline = ini.GetBoolValue(S, "underline", textUnderline);
// colors
textForegroundColor = Color{
ini.GetValue(S, "textForegroundColor",
textForegroundColor.toHexString().c_str())
};
textBackgroundColor = Color{
ini.GetValue(S, "textBackgroundColor",
textBackgroundColor.toHexString().c_str())
};
textEdgeColor = Color{
ini.GetValue(S, "textEdgeColor",
textEdgeColor.toHexString().c_str())
};
// enums (fallback via default string)
try {
textEdgeType = enumFromString<EdgeType>(
ini.GetValue(S, "textEdgeType",
enumToString(textEdgeType).c_str()));
} catch (...) {
}
try {
fontStyle = enumFromString<FontStyle>(
ini.GetValue(S, "fontStyle",
enumToString(fontStyle).c_str()));
} catch (...) {
}
try {
textAlignment = enumFromString<TextAlignment>(
ini.GetValue(S, "textAlignment",
enumToString(textAlignment).c_str()));
} catch (...) {
}
fontSizePercent = static_cast<int>(
ini.GetLongValue(S, "fontSizePercent",
fontSizePercent));
horizontalMargin = static_cast<int>(
ini.GetLongValue(S, "horizontalMargin",
horizontalMargin));
verticalMargin = static_cast<int>(
ini.GetLongValue(S, "verticalMargin",
verticalMargin));
verticalSpacing = static_cast<int>(
ini.GetLongValue(S, "verticalSpacing",
verticalSpacing));
totalDisplayLines = static_cast<int>(
ini.GetLongValue(S, "totalDisplayLines",
totalDisplayLines));
maxCharsPerLine = static_cast<int>(
ini.GetLongValue(S, "maxCharsPerLine",
maxCharsPerLine));
usernameSeparator = ini.GetValue(S, "usernameSeparator",
usernameSeparator.c_str());
return true;
}
};
struct User {
std::string name;
Color color;
};
// A single parsed chat message.
struct ChatMessage {
uint64_t time = 0; // Timestamp in milliseconds
User user;
std::string message;
};
// A single wrapped chat line.
struct ChatLine {
std::optional<User> user;
std::string text;
};
// A batch represents the current accumulated chat lines at a given timestamp.
struct Batch {
int time;
std::deque<ChatLine> lines;
};
std::pair<std::string, std::vector<std::string>> wrapMessage(std::string username,
std::string separator,
const std::string &message,
int maxWidth) {
std::vector<std::string> lines;
int availableSpace = maxWidth;
if (utf8_length(username) > maxWidth) {
username = utf8_substr(username, maxWidth);
lines.push_back("");
} else {
availableSpace -= utf8_length(username);
}
if (utf8_length(separator) > availableSpace) {
separator = utf8_substr(separator, availableSpace);
}
if (utf8_length(separator) > 0) {
lines.push_back(separator);
availableSpace -= utf8_length(separator);
}
std::istringstream iss(message);
std::vector<std::string> words;
std::string word;
bool firstWord = true;
while (iss >> word) {
bool bigWord = false;
while (utf8_length(word) > maxWidth) {
bigWord = true;
if (availableSpace < 2) {
availableSpace = maxWidth;
lines.push_back(utf8_substr(word, availableSpace));
firstWord = false;
} else {
if (!firstWord) {
lines.back() += " ";
availableSpace--;
}
lines.back() += utf8_substr(word, availableSpace);
firstWord = false;
}
word = utf8_consume(word, availableSpace);// add split
availableSpace = 0;
}
if (bigWord) {
//if (utf8_length(word) < availableSpace) word += " ";
lines.push_back(word);
availableSpace = maxWidth - utf8_length(word);
firstWord = false;
continue;
}
if (utf8_length(word) < availableSpace) {
if (!firstWord) {
lines.back() += " ";
availableSpace--;
}
lines.back() += word;
availableSpace -= utf8_length(word);
} else {
//if (utf8_length(word) < maxWidth) word += " ";
lines.push_back(word);
availableSpace = maxWidth - utf8_length(word);
}
firstWord = false;
}
// for (const auto& line :lines){
// assert(utf8_length(line)<=maxWidth);
// }
return {username, lines};
}
std::string generateXML(const std::vector<ChatMessage> &messages, const ChatParams ¶ms) {
using namespace tinyxml2;
XMLDocument doc;
std::map<Color, std::string> colors;
colors[params.textForegroundColor] = "";
for (const auto &m: messages) {
colors[m.user.color] = "";
}
std::vector<Batch> batches;
std::deque<ChatLine> currentLines;
for (const auto &msg: messages) {
auto [username, wrapped] = wrapMessage(msg.user.name, params.usernameSeparator, msg.message,
params.maxCharsPerLine);
if (wrapped.empty())
continue;
currentLines.emplace_back(std::make_optional<User>(username, msg.user.color), wrapped[0]);
if (currentLines.size() > params.totalDisplayLines) currentLines.pop_front();
for (size_t i = 1; i < wrapped.size(); ++i) {
currentLines.emplace_back(std::nullopt, wrapped[i]);
if (currentLines.size() > params.totalDisplayLines) currentLines.pop_front();
}
if (!batches.empty() && batches.back().time == msg.time)
continue;
batches.emplace_back(msg.time, currentLines);
}
XMLElement *root = doc.NewElement("timedtext");
root->SetAttribute("format", "3");
doc.InsertFirstChild(root);
XMLElement *head = doc.NewElement("head");
root->InsertEndChild(head);
XMLElement *body = doc.NewElement("body");
root->InsertEndChild(body);
// Create pen elements for each unique color.
int penIndex = 0;
for (auto &kv: colors) {
const Color &color = kv.first;
XMLElement *pen = doc.NewElement("pen");
pen->SetAttribute("id", std::to_string(penIndex).c_str());
pen->SetAttribute("b", (params.textBold ? "1" : "0"));
pen->SetAttribute("i", (params.textItalic ? "1" : "0"));
pen->SetAttribute("u", (params.textUnderline ? "1" : "0"));
// Use the friendly textForegroundColor if it differs from default white.
pen->SetAttribute("fc", static_cast<std::string>(color).c_str());
pen->SetAttribute("fo", std::to_string(params.textForegroundColor.a).c_str());
pen->SetAttribute("bc", static_cast<std::string>(params.textBackgroundColor).c_str());
pen->SetAttribute("bo", std::to_string(params.textBackgroundColor.a).c_str());
// Set edge attributes if provided.
std::string textEdgeType = enumToIntString(params.textEdgeType);
if (!textEdgeType.empty()) {
pen->SetAttribute("ec", static_cast<std::string>(params.textEdgeColor).c_str());
pen->SetAttribute("et", textEdgeType.c_str());
}
pen->SetAttribute("fs", enumToIntString(params.fontStyle).c_str());
pen->SetAttribute("sz", std::to_string(params.fontSizePercent).c_str());
head->InsertEndChild(pen);
kv.second = std::to_string(penIndex);
penIndex++;
}
// Create workspace element for positioning.
XMLElement *ws = doc.NewElement("ws");
ws->SetAttribute("id", "1"); // default workspace id
ws->SetAttribute("ju", enumToIntString(params.textAlignment).c_str());
head->InsertEndChild(ws);
// Create write positioning (wp) elements.
for (int i = 0; i < params.totalDisplayLines; ++i) {
XMLElement *wp = doc.NewElement("wp");
wp->SetAttribute("id", std::to_string(i).c_str());
wp->SetAttribute("ap", "0"); // anchor point
wp->SetAttribute("ah", std::to_string(params.horizontalMargin).c_str());
wp->SetAttribute("av", std::to_string(i * params.verticalSpacing).c_str());
head->InsertEndChild(wp);
}
// Zero-width space (ZWSP) as a UTF-8 string.
const char *ZWSP = "\xE2\x80\x8B";
// Build the body: add <p> elements from each batch;
for (size_t batchIndex = 0; batchIndex + 1 < batches.size(); ++batchIndex) {
const Batch &batch = batches[batchIndex];
const Batch &nextBatch = batches[batchIndex + 1];
auto defaultPen = colors[params.textForegroundColor];
for (const auto &[idx, line]: batch.lines | std::ranges::views::enumerate) {
XMLElement *pElem = doc.NewElement("p");
pElem->SetAttribute("t", std::to_string(batch.time).c_str());
int duration = nextBatch.time - batch.time;
pElem->SetAttribute("d", std::to_string(duration).c_str());
pElem->SetAttribute("wp", std::to_string(idx).c_str());
pElem->SetAttribute("ws", "1");
pElem->SetAttribute("p", defaultPen.c_str());
pElem->LinkEndChild(doc.NewText(""));
if (line.user.has_value()) {
XMLElement *sUser = doc.NewElement("s");
sUser->SetAttribute("p", colors[line.user->color].c_str());
std::string userText = line.user->name;
sUser->SetText(userText.c_str());
pElem->InsertEndChild(sUser);
pElem->LinkEndChild(doc.NewText(ZWSP));
}
XMLElement *sText = doc.NewElement("s");
sText->SetAttribute("p", defaultPen.c_str());
sText->SetText(line.text.c_str());
pElem->InsertEndChild(sText);
pElem->LinkEndChild(doc.NewText(""));
body->InsertEndChild(pElem);
}
}
XMLPrinter printer;
doc.Print(&printer);
return printer.CStr();
}
Color getRandomColor(const std::string &username) {
std::vector<Color> defaultColors = {"#ff0000", "#0000ff", "#008000", "#b22222", "#ff7f50",
"#9acd32", "#ff4500", "#2e8b57", "#daa520", "#d2691e",
"#5f9ea0", "#1e90ff", "#ff69b4", "#8a2be2", "#00ff7f"};
std::hash<std::string> hasher;
return defaultColors[hasher(username) % defaultColors.size()];
}