-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
822 lines (704 loc) · 29.5 KB
/
main.cpp
File metadata and controls
822 lines (704 loc) · 29.5 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
//=============================================================================
// Steam Leaderboard Score Uploader
//
// A standalone CLI tool that uploads scores to Steam leaderboards.
// Reads configuration from leaderboards.ini, auto-detects leaderboard
// metadata, shows top 10 entries, and uploads scores.
//
// Usage:
// ./steam_leaderboards
//
// All configuration is read from leaderboards.ini in the same directory.
//=============================================================================
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define SLEEP_MS(ms) Sleep(ms)
static void SetSteamEnv(const char* appId) {
_putenv_s("SteamAppId", appId);
_putenv_s("SteamGameId", appId);
}
static void SuppressSteamOutput() {
freopen("NUL", "w", stderr);
}
static void RestoreSteamOutput() {
freopen("CON", "w", stderr);
}
#else
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define SLEEP_MS(ms) usleep((ms) * 1000)
static void SetSteamEnv(const char* appId) {
setenv("SteamAppId", appId, 1);
setenv("SteamGameId", appId, 1);
}
static void SuppressSteamOutput() {
freopen("/dev/null", "w", stderr);
}
static void RestoreSteamOutput() {
freopen("/dev/tty", "w", stderr);
}
#endif
#include "steam/steam_api.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <chrono>
#include <algorithm>
//=============================================================================
// Console Colors (ANSI escape codes, works on modern terminals + Win10+)
//=============================================================================
#define CLR_RESET "\033[0m"
#define CLR_BOLD "\033[1m"
#define CLR_DIM "\033[2m"
#define CLR_RED "\033[91m"
#define CLR_GREEN "\033[92m"
#define CLR_YELLOW "\033[93m"
#define CLR_BLUE "\033[94m"
#define CLR_MAGENTA "\033[95m"
#define CLR_CYAN "\033[96m"
#define CLR_WHITE "\033[97m"
//=============================================================================
// INI Parser — Simple, no external dependencies
//=============================================================================
struct IniSection {
std::string name;
std::map<std::string, std::string> values;
};
struct IniFile {
std::vector<IniSection> sections;
bool load(const char* filename) {
FILE* f = fopen(filename, "r");
if (!f) return false;
char line[1024];
IniSection* current = nullptr;
while (fgets(line, sizeof(line), f)) {
// Strip trailing newline/carriage return
size_t len = strlen(line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r'))
line[--len] = '\0';
// Skip empty lines and comments
const char* p = line;
while (*p == ' ' || *p == '\t') p++;
if (*p == '\0' || *p == ';' || *p == '#')
continue;
// Section header
if (*p == '[') {
const char* end = strchr(p, ']');
if (end) {
sections.push_back({});
current = §ions.back();
current->name = std::string(p + 1, end);
}
continue;
}
// Key = Value
if (current) {
const char* eq = strchr(p, '=');
if (eq) {
std::string key(p, eq);
std::string val(eq + 1);
// Trim whitespace
auto trim = [](std::string& s) {
size_t start = s.find_first_not_of(" \t");
size_t end = s.find_last_not_of(" \t");
if (start == std::string::npos) { s.clear(); return; }
s = s.substr(start, end - start + 1);
};
trim(key);
trim(val);
// Strip inline comments
size_t comment = val.find(';');
if (comment != std::string::npos) {
val = val.substr(0, comment);
auto trim2 = [](std::string& s) {
size_t end = s.find_last_not_of(" \t");
if (end == std::string::npos) { s.clear(); return; }
s = s.substr(0, end + 1);
};
trim2(val);
}
current->values[key] = val;
}
}
}
fclose(f);
return true;
}
const IniSection* findSection(const std::string& name) const {
for (auto& s : sections) {
if (s.name == name) return &s;
}
return nullptr;
}
};
//=============================================================================
// Leaderboard entry from INI
//=============================================================================
struct LeaderboardTask {
std::string name;
int32_t score;
ELeaderboardUploadScoreMethod method;
// Filled in at runtime after FindLeaderboard
SteamLeaderboard_t handle = 0;
ELeaderboardSortMethod sortMethod = k_ELeaderboardSortMethodNone;
ELeaderboardDisplayType displayType = k_ELeaderboardDisplayTypeNone;
int entryCount = 0;
bool found = false;
};
//=============================================================================
// Score formatting helpers
//=============================================================================
static const char* SortMethodStr(ELeaderboardSortMethod m) {
switch (m) {
case k_ELeaderboardSortMethodAscending: return "Ascending (lower is better)";
case k_ELeaderboardSortMethodDescending: return "Descending (higher is better)";
default: return "Unknown";
}
}
static const char* DisplayTypeStr(ELeaderboardDisplayType t) {
switch (t) {
case k_ELeaderboardDisplayTypeNumeric: return "Numeric";
case k_ELeaderboardDisplayTypeTimeSeconds: return "Time (Seconds)";
case k_ELeaderboardDisplayTypeTimeMilliSeconds: return "Time (Milliseconds)";
default: return "Unknown";
}
}
static std::string FormatScore(int32_t score, ELeaderboardDisplayType displayType) {
char buf[128];
switch (displayType) {
case k_ELeaderboardDisplayTypeTimeSeconds: {
int hours = score / 3600;
int mins = (score % 3600) / 60;
int secs = score % 60;
if (hours > 0)
snprintf(buf, sizeof(buf), "%d:%02d:%02d", hours, mins, secs);
else
snprintf(buf, sizeof(buf), "%d:%02d", mins, secs);
return buf;
}
case k_ELeaderboardDisplayTypeTimeMilliSeconds: {
int totalSecs = score / 1000;
int ms = score % 1000;
int hours = totalSecs / 3600;
int mins = (totalSecs % 3600) / 60;
int secs = totalSecs % 60;
if (hours > 0)
snprintf(buf, sizeof(buf), "%d:%02d:%02d.%03d", hours, mins, secs, ms);
else
snprintf(buf, sizeof(buf), "%d:%02d.%03d", mins, secs, ms);
return buf;
}
case k_ELeaderboardDisplayTypeNumeric:
default: {
// Add thousand separators
std::string raw = std::to_string(score);
std::string result;
int count = 0;
for (int i = (int)raw.size() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0)
result = "," + result;
result = raw[i] + result;
count++;
}
return result;
}
}
}
//=============================================================================
// Main Application Class — manages async Steam callbacks
//=============================================================================
class CSteamLeaderboardUploader {
public:
CSteamLeaderboardUploader() = default;
bool Init(const char* appId) {
SetSteamEnv(appId);
// Suppress Steam's noisy debug output (breakpad, minidump, etc.)
SuppressSteamOutput();
bool initOk = SteamAPI_Init();
RestoreSteamOutput();
if (!initOk) {
printf(CLR_RED "[!] Failed to initialize Steam API.\n" CLR_RESET);
printf(CLR_DIM " Make sure Steam is running and you are logged in.\n" CLR_RESET);
return false;
}
const char* personaName = SteamFriends()->GetPersonaName();
CSteamID userId = SteamUser()->GetSteamID();
printf(CLR_GREEN "[+] " CLR_RESET "Logged in as: "
CLR_CYAN "%s" CLR_RESET " (%llu)\n\n",
personaName, userId.ConvertToUint64());
return true;
}
void Shutdown() {
SteamAPI_Shutdown();
}
//--- FindLeaderboard ---
bool FindLeaderboard(LeaderboardTask& task) {
m_currentTask = &task;
m_findDone = false;
m_findFailed = false;
SteamAPICall_t hCall = SteamUserStats()->FindLeaderboard(task.name.c_str());
m_findResult.Set(hCall, this, &CSteamLeaderboardUploader::OnFindLeaderboard);
// Pump callbacks until done or timeout
if (!WaitForResult(m_findDone, m_findFailed, 15.0)) {
printf(CLR_RED " [!] Timeout finding leaderboard.\n" CLR_RESET);
return false;
}
if (m_findFailed) {
printf(CLR_RED " [!] Leaderboard \"%s\" not found.\n" CLR_RESET, task.name.c_str());
return false;
}
return true;
}
//--- DownloadLeaderboardEntries (Top 10) ---
bool DownloadTop10(LeaderboardTask& task) {
m_currentTask = &task;
m_downloadDone = false;
m_downloadFailed = false;
m_downloadedEntries.clear();
SteamAPICall_t hCall = SteamUserStats()->DownloadLeaderboardEntries(
task.handle, k_ELeaderboardDataRequestGlobal, 1, 10);
m_downloadResult.Set(hCall, this, &CSteamLeaderboardUploader::OnDownloadEntries);
if (!WaitForResult(m_downloadDone, m_downloadFailed, 15.0)) {
printf(CLR_YELLOW " [!] Timeout downloading leaderboard entries.\n" CLR_RESET);
return false;
}
return !m_downloadFailed;
}
//--- UploadLeaderboardScore ---
bool UploadScore(LeaderboardTask& task) {
m_currentTask = &task;
m_uploadDone = false;
m_uploadFailed = false;
SteamAPICall_t hCall = SteamUserStats()->UploadLeaderboardScore(
task.handle, task.method, task.score, nullptr, 0);
m_uploadResult.Set(hCall, this, &CSteamLeaderboardUploader::OnUploadScore);
if (!WaitForResult(m_uploadDone, m_uploadFailed, 15.0)) {
printf(CLR_RED " [!] Timeout uploading score.\n" CLR_RESET);
return false;
}
return !m_uploadFailed;
}
// Data from the last download
struct DownloadedEntry {
int32_t rank;
int32_t score;
std::string playerName;
CSteamID steamId;
};
std::vector<DownloadedEntry> m_downloadedEntries;
// Upload result data
bool m_scoreChanged = false;
int m_newRank = 0;
int m_prevRank = 0;
private:
LeaderboardTask* m_currentTask = nullptr;
// FindLeaderboard
bool m_findDone = false;
bool m_findFailed = false;
CCallResult<CSteamLeaderboardUploader, LeaderboardFindResult_t> m_findResult;
// DownloadLeaderboardEntries
bool m_downloadDone = false;
bool m_downloadFailed = false;
CCallResult<CSteamLeaderboardUploader, LeaderboardScoresDownloaded_t> m_downloadResult;
// UploadLeaderboardScore
bool m_uploadDone = false;
bool m_uploadFailed = false;
CCallResult<CSteamLeaderboardUploader, LeaderboardScoreUploaded_t> m_uploadResult;
//--- Callback: FindLeaderboard ---
void OnFindLeaderboard(LeaderboardFindResult_t* pResult, bool bIOFailure) {
if (bIOFailure || !pResult->m_bLeaderboardFound) {
m_findFailed = true;
} else {
m_currentTask->handle = pResult->m_hSteamLeaderboard;
m_currentTask->found = true;
// Auto-detect metadata
m_currentTask->sortMethod = SteamUserStats()->GetLeaderboardSortMethod(m_currentTask->handle);
m_currentTask->displayType = SteamUserStats()->GetLeaderboardDisplayType(m_currentTask->handle);
m_currentTask->entryCount = SteamUserStats()->GetLeaderboardEntryCount(m_currentTask->handle);
}
m_findDone = true;
}
//--- Callback: DownloadLeaderboardEntries ---
void OnDownloadEntries(LeaderboardScoresDownloaded_t* pResult, bool bIOFailure) {
if (bIOFailure) {
m_downloadFailed = true;
} else {
int count = pResult->m_cEntryCount;
if (count > 10) count = 10;
for (int i = 0; i < count; i++) {
LeaderboardEntry_t entry;
SteamUserStats()->GetDownloadedLeaderboardEntry(
pResult->m_hSteamLeaderboardEntries, i, &entry, nullptr, 0);
DownloadedEntry de;
de.rank = entry.m_nGlobalRank;
de.score = entry.m_nScore;
de.steamId = entry.m_steamIDUser;
de.playerName = SteamFriends()->GetFriendPersonaName(entry.m_steamIDUser);
m_downloadedEntries.push_back(de);
}
}
m_downloadDone = true;
}
//--- Callback: UploadLeaderboardScore ---
void OnUploadScore(LeaderboardScoreUploaded_t* pResult, bool bIOFailure) {
if (bIOFailure || !pResult->m_bSuccess) {
m_uploadFailed = true;
} else {
m_scoreChanged = pResult->m_bScoreChanged != 0;
m_newRank = pResult->m_nGlobalRankNew;
m_prevRank = pResult->m_nGlobalRankPrevious;
}
m_uploadDone = true;
}
//--- Wait loop ---
bool WaitForResult(bool& done, bool& failed, double timeoutSec) {
auto start = std::chrono::steady_clock::now();
while (!done) {
SteamAPI_RunCallbacks();
SLEEP_MS(50);
auto now = std::chrono::steady_clock::now();
double elapsed = std::chrono::duration<double>(now - start).count();
if (elapsed > timeoutSec)
return false;
}
return true;
}
};
//=============================================================================
// Parse upload method string
//=============================================================================
static bool ParseUploadMethod(const std::string& str, ELeaderboardUploadScoreMethod& out) {
std::string lower = str;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower == "keepbest" || lower == "keep_best" || lower == "1") {
out = k_ELeaderboardUploadScoreMethodKeepBest;
return true;
}
if (lower == "forceupdate" || lower == "force_update" || lower == "2") {
out = k_ELeaderboardUploadScoreMethodForceUpdate;
return true;
}
return false;
}
static const char* UploadMethodStr(ELeaderboardUploadScoreMethod m) {
switch (m) {
case k_ELeaderboardUploadScoreMethodKeepBest: return "KeepBest";
case k_ELeaderboardUploadScoreMethodForceUpdate: return "ForceUpdate";
default: return "Unknown";
}
}
//=============================================================================
// Print helpers
//=============================================================================
// Repeat a UTF-8 string N times (for box-drawing chars like ─ which are multi-byte)
static std::string RepeatStr(const char* s, int n) {
std::string result;
for (int i = 0; i < n; i++) result += s;
return result;
}
// Calculate display width (terminal columns) of a UTF-8 string
static int Utf8DisplayWidth(const std::string& s) {
int width = 0;
for (size_t i = 0; i < s.size(); ) {
unsigned char c = (unsigned char)s[i];
if (c < 0x80) { width += 1; i += 1; } // ASCII
else if (c < 0xC0) { i += 1; } // continuation byte (skip)
else if (c < 0xE0) { width += 1; i += 2; } // 2-byte (Latin ext, Cyrillic)
else if (c < 0xF0) {
// 3-byte: CJK fullwidth chars (U+1100..U+FFDC range, simplified)
// Most common CJK range: U+2E80-U+9FFF, U+F900-U+FAFF
uint32_t cp = ((c & 0x0F) << 12) | (((unsigned char)s[i+1] & 0x3F) << 6) | ((unsigned char)s[i+2] & 0x3F);
if ((cp >= 0x2E80 && cp <= 0x9FFF) || (cp >= 0xF900 && cp <= 0xFAFF) ||
(cp >= 0xFE30 && cp <= 0xFE6F) || (cp >= 0xFF01 && cp <= 0xFF60) ||
(cp >= 0xFFE0 && cp <= 0xFFE6))
width += 2; // fullwidth
else
width += 1; // normal width
i += 3;
}
else { width += 2; i += 4; } // 4-byte (emoji etc, usually double-width)
}
return width;
}
// Truncate a UTF-8 string to fit within maxDisplayCols columns, appending "..."
static std::string TruncateUtf8(const std::string& s, int maxDisplayCols) {
int width = 0;
size_t lastPos = 0;
for (size_t i = 0; i < s.size(); ) {
unsigned char c = (unsigned char)s[i];
int charWidth = 1;
int charBytes = 1;
if (c < 0x80) { charBytes = 1; charWidth = 1; }
else if (c < 0xC0) { charBytes = 1; charWidth = 0; } // continuation
else if (c < 0xE0) { charBytes = 2; charWidth = 1; }
else if (c < 0xF0) {
charBytes = 3;
uint32_t cp = ((c & 0x0F) << 12) | (((unsigned char)s[i+1] & 0x3F) << 6) | ((unsigned char)s[i+2] & 0x3F);
if ((cp >= 0x2E80 && cp <= 0x9FFF) || (cp >= 0xF900 && cp <= 0xFAFF) ||
(cp >= 0xFE30 && cp <= 0xFE6F) || (cp >= 0xFF01 && cp <= 0xFF60) ||
(cp >= 0xFFE0 && cp <= 0xFFE6))
charWidth = 2;
else
charWidth = 1;
}
else { charBytes = 4; charWidth = 2; }
if (width + charWidth > maxDisplayCols - 3) { // -3 for "..."
return s.substr(0, lastPos) + "...";
}
width += charWidth;
i += charBytes;
lastPos = i;
}
return s; // no truncation needed
}
static void PrintLeaderboardInfo(const LeaderboardTask& task) {
printf(CLR_BOLD " ├─ Sort: " CLR_RESET "%s\n", SortMethodStr(task.sortMethod));
printf(CLR_BOLD " ├─ Display: " CLR_RESET "%s\n", DisplayTypeStr(task.displayType));
printf(CLR_BOLD " ├─ Entries: " CLR_RESET "%d\n", task.entryCount);
}
static void PrintScorePreview(const LeaderboardTask& task) {
std::string formatted = FormatScore(task.score, task.displayType);
printf(CLR_BOLD " ├─ Score: " CLR_RESET CLR_WHITE "%d" CLR_RESET, task.score);
if (task.displayType != k_ELeaderboardDisplayTypeNumeric) {
printf(" → " CLR_CYAN "%s" CLR_RESET, formatted.c_str());
}
printf("\n");
printf(CLR_BOLD " ├─ Method: " CLR_RESET "%s\n", UploadMethodStr(task.method));
// Warning for time-based leaderboards
if (task.displayType == k_ELeaderboardDisplayTypeTimeSeconds) {
printf(CLR_YELLOW " │ ⚠ This leaderboard uses TIME IN SECONDS.\n" CLR_RESET);
printf(CLR_YELLOW " │ Your raw score %d will display as \"%s\"\n" CLR_RESET,
task.score, formatted.c_str());
} else if (task.displayType == k_ELeaderboardDisplayTypeTimeMilliSeconds) {
printf(CLR_YELLOW " │ ⚠ This leaderboard uses TIME IN MILLISECONDS.\n" CLR_RESET);
printf(CLR_YELLOW " │ Your raw score %d will display as \"%s\"\n" CLR_RESET,
task.score, formatted.c_str());
}
}
static void PrintTop10(const CSteamLeaderboardUploader& uploader, ELeaderboardDisplayType displayType) {
if (uploader.m_downloadedEntries.empty()) {
printf(CLR_DIM " │ (no entries on this leaderboard)\n" CLR_RESET);
return;
}
// Calculate dynamic column widths using display width (handles UTF-8)
int maxNameCols = 6; // minimum "Player" header width
int maxScoreCols = 5; // minimum "Score" header width
for (auto& e : uploader.m_downloadedEntries) {
std::string truncated = TruncateUtf8(e.playerName, 25);
int nameCols = Utf8DisplayWidth(truncated);
if (nameCols > maxNameCols) maxNameCols = nameCols;
std::string fs = FormatScore(e.score, displayType);
int scoreCols = (int)fs.length(); // scores are always ASCII
if (scoreCols > maxScoreCols) maxScoreCols = scoreCols;
}
// Add padding
maxNameCols += 1;
maxScoreCols += 1;
// Build box-drawing horizontal bars
std::string rankBar = RepeatStr("─", 6);
std::string nBar = RepeatStr("─", maxNameCols + 2);
std::string sBar = RepeatStr("─", maxScoreCols + 2);
printf(CLR_BOLD " ├─ Top %d:\n" CLR_RESET, (int)uploader.m_downloadedEntries.size());
printf(CLR_DIM " │ ┌%s┬%s┬%s┐\n", rankBar.c_str(), nBar.c_str(), sBar.c_str());
printf(" │ │ Rank │ %-*s │ %-*s │\n", maxNameCols, "Player", maxScoreCols, "Score");
printf(" │ ├%s┼%s┼%s┤\n" CLR_RESET, rankBar.c_str(), nBar.c_str(), sBar.c_str());
for (auto& e : uploader.m_downloadedEntries) {
std::string formattedScore = FormatScore(e.score, displayType);
std::string name = TruncateUtf8(e.playerName, 25);
// Adjust printf width: add byte/display difference for multi-byte chars
int byteLen = (int)name.size();
int displayLen = Utf8DisplayWidth(name);
int namePadWidth = maxNameCols + (byteLen - displayLen);
printf(CLR_DIM " │ │ " CLR_RESET CLR_YELLOW "#%-3d" CLR_RESET
CLR_DIM " │ " CLR_RESET "%-*s" CLR_DIM " │ " CLR_RESET
CLR_GREEN "%-*s" CLR_RESET CLR_DIM " │\n" CLR_RESET,
e.rank, namePadWidth, name.c_str(), maxScoreCols, formattedScore.c_str());
}
printf(CLR_DIM " │ └%s┴%s┴%s┘\n" CLR_RESET, rankBar.c_str(), nBar.c_str(), sBar.c_str());
}
//=============================================================================
// Main
//=============================================================================
int main(int argc, char* argv[]) {
(void)argc; (void)argv;
// Enable ANSI colors on Windows 10+
#ifdef _WIN32
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
SetConsoleMode(hOut, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
#endif
//--- Load INI ---
IniFile ini;
if (!ini.load("leaderboards.ini")) {
printf(CLR_RED "[!] Failed to open leaderboards.ini\n" CLR_RESET);
printf(CLR_DIM " Create a leaderboards.ini file in the same directory.\n" CLR_RESET);
printf(CLR_DIM " Example:\n\n" CLR_RESET);
printf(CLR_DIM " [settings]\n");
printf(" appid = 12345\n");
printf(" upload_method = ForceUpdate\n");
printf(" auto_confirm = false\n\n");
printf(" [My Leaderboard Name]\n");
printf(" score = 1500\n" CLR_RESET);
return 1;
}
//--- Parse [settings] section ---
const IniSection* settings = ini.findSection("settings");
if (!settings) {
printf(CLR_RED "[!] Missing [settings] section in leaderboards.ini\n" CLR_RESET);
return 1;
}
auto getVal = [](const IniSection* sec, const std::string& key) -> std::string {
auto it = sec->values.find(key);
if (it != sec->values.end()) return it->second;
return "";
};
std::string appId = getVal(settings, "appid");
if (appId.empty()) {
printf(CLR_RED "[!] Missing 'appid' in [settings]\n" CLR_RESET);
return 1;
}
std::string methodStr = getVal(settings, "upload_method");
if (methodStr.empty()) methodStr = "KeepBest";
ELeaderboardUploadScoreMethod globalMethod;
if (!ParseUploadMethod(methodStr, globalMethod)) {
printf(CLR_RED "[!] Invalid upload_method '%s'. Use KeepBest or ForceUpdate.\n" CLR_RESET,
methodStr.c_str());
return 1;
}
// Auto-confirm from INI
bool autoConfirm = false;
{
std::string acStr = getVal(settings, "auto_confirm");
std::transform(acStr.begin(), acStr.end(), acStr.begin(), ::tolower);
autoConfirm = (acStr == "true" || acStr == "yes" || acStr == "1");
}
//--- Build leaderboard task list ---
std::vector<LeaderboardTask> tasks;
for (auto& sec : ini.sections) {
if (sec.name == "settings") continue;
LeaderboardTask task;
task.name = sec.name;
auto scoreIt = sec.values.find("score");
if (scoreIt == sec.values.end()) {
printf(CLR_YELLOW "[!] Warning: Section [%s] has no 'score' key, skipping.\n" CLR_RESET,
sec.name.c_str());
continue;
}
// Strip commas/dots (thousand separators) so "23,840,027" works
std::string scoreStr = scoreIt->second;
scoreStr.erase(std::remove(scoreStr.begin(), scoreStr.end(), ','), scoreStr.end());
task.score = atoi(scoreStr.c_str());
// Per-leaderboard method override
auto methodIt = sec.values.find("upload_method");
if (methodIt != sec.values.end()) {
if (!ParseUploadMethod(methodIt->second, task.method)) {
printf(CLR_YELLOW "[!] Warning: Invalid upload_method in [%s], using global.\n" CLR_RESET,
sec.name.c_str());
task.method = globalMethod;
}
} else {
task.method = globalMethod;
}
tasks.push_back(task);
}
if (tasks.empty()) {
printf(CLR_RED "[!] No leaderboard sections found in leaderboards.ini\n" CLR_RESET);
return 1;
}
//--- Initialize Steam ---
printf(CLR_BOLD "[*] " CLR_RESET "Initializing Steam API...\n");
CSteamLeaderboardUploader uploader;
if (!uploader.Init(appId.c_str())) {
return 1;
}
//--- Process each leaderboard ---
int successCount = 0;
int failCount = 0;
for (int i = 0; i < (int)tasks.size(); i++) {
LeaderboardTask& task = tasks[i];
// Build dynamic-width header box
int textLen = snprintf(nullptr, 0, " Leaderboard %d/%d: \"%s\"",
i + 1, (int)tasks.size(), task.name.c_str());
int boxWidth = textLen + 1; // +1 for trailing padding
if (boxWidth < 40) boxWidth = 40;
std::string topBar = RepeatStr("─", boxWidth);
printf(CLR_BOLD CLR_BLUE " ┌%s┐\n", topBar.c_str());
printf(" │" CLR_RESET CLR_BOLD " Leaderboard %d/%d: " CLR_CYAN "\"%s\"" CLR_RESET,
i + 1, (int)tasks.size(), task.name.c_str());
// Pad to align right border
for (int p = textLen; p < boxWidth; p++) printf(" ");
printf(CLR_BOLD CLR_BLUE "│\n");
printf(" └%s┘\n" CLR_RESET, topBar.c_str());
//--- Step 1: Find leaderboard ---
printf(" Finding leaderboard...");
fflush(stdout);
if (!uploader.FindLeaderboard(task)) {
failCount++;
printf("\n");
continue;
}
printf(CLR_GREEN " found!\n" CLR_RESET);
//--- Step 2: Print leaderboard info ---
PrintLeaderboardInfo(task);
//--- Step 3: Show score & method (before top 10, so user sees context) ---
PrintScorePreview(task);
//--- Step 4: Download and display top 10 ---
if (uploader.DownloadTop10(task)) {
PrintTop10(uploader, task.displayType);
}
//--- Step 5: Confirmation ---
if (!autoConfirm) {
printf(CLR_BOLD CLR_MAGENTA "\n Proceed with uploading? (y/N): " CLR_RESET);
fflush(stdout);
char response[16] = {0};
if (fgets(response, sizeof(response), stdin)) {
// Trim
size_t rlen = strlen(response);
while (rlen > 0 && (response[rlen-1] == '\n' || response[rlen-1] == '\r'))
response[--rlen] = '\0';
if (response[0] != 'y' && response[0] != 'Y') {
printf(CLR_YELLOW " [~] Skipped.\n\n" CLR_RESET);
continue;
}
} else {
printf(CLR_YELLOW " [~] No input, skipping.\n\n" CLR_RESET);
continue;
}
}
//--- Step 6: Upload! ---
printf(" Uploading score %d...", task.score);
fflush(stdout);
if (uploader.UploadScore(task)) {
printf(CLR_GREEN " success!\n" CLR_RESET);
printf(CLR_BOLD " ├─ New rank: " CLR_RESET CLR_GREEN "#%d\n" CLR_RESET, uploader.m_newRank);
if (uploader.m_prevRank > 0)
printf(CLR_BOLD " └─ Previous rank: " CLR_RESET "#%d\n", uploader.m_prevRank);
else
printf(CLR_BOLD " └─ Previous rank: " CLR_RESET CLR_DIM "(new entry)\n" CLR_RESET);
successCount++;
} else {
printf(CLR_RED " FAILED!\n" CLR_RESET);
failCount++;
}
printf("\n");
}
//--- Summary ---
if (failCount == 0) {
printf(CLR_GREEN " [+] All done! %d/%d leaderboard(s) updated.\n" CLR_RESET,
successCount, (int)tasks.size());
} else {
printf(CLR_YELLOW " [~] Done. %d succeeded, %d failed/skipped out of %d.\n" CLR_RESET,
successCount, failCount, (int)tasks.size());
}
printf("\n");
uploader.Shutdown();
return failCount > 0 ? 1 : 0;
}