Repository navigation
Expand file tree
/
Copy pathstevensTerminal.cpp
More file actions
1425 lines (1263 loc) · 48.5 KB
/
Copy pathstevensTerminal.cpp
File metadata and controls
1425 lines (1263 loc) · 48.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
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
/**
* stevensTerminal.cpp
* Implementation file for stevensTerminal library
* Migrated from header-only to compiled library for faster build times
*/
#include "stevensTerminal.hpp"
#if defined(__linux__)
#include <sys/ioctl.h>
#include <unistd.h>
#endif
#include <limits>
#include <fstream>
#include <spdlog/spdlog.h>
#include "classes/PrintToken.hpp"
#include "classes/PrintTokenHelper.hpp"
#include "classes/WindowManager.hpp"
#include <stevensMapLib.hpp>
#include "subnamespaces/Colors.hpp"
#include "subnamespaces/Input.hpp"
#include "subnamespaces/ParticleFX/ParticleWindowRegistry.hpp"
#include "subnamespaces/Styling.hpp"
namespace stevensTerminal
{
// ==================== GLOBAL VARIABLE DEFINITIONS ====================
std::map<std::string, DisplayMode> displayModes = {
{"very small", DisplayMode({-1,-1},{79,23},18)},
{"small", DisplayMode({80,24},{119,39},18)},
{"regular", DisplayMode({120,40},{-1,-1},24)}
};
std::string currentDisplayMode = "regular";
bool textStyling = true;
bool curses_colorCompatible = false;
// ==================== CORE.HPP IMPLEMENTATIONS ====================
WindowManager& windowManager() {
static WindowManager instance;
return instance;
}
#if defined(_WIN32)
std::pair<int, int> get_screen_size() {
// CONOUT$, not STD_OUTPUT_HANDLE: PDCurses' wincon backend draws into its own console
// screen buffer and makes that the active one, leaving STD_OUTPUT_HANDLE on the original
// buffer - which stays at its launch size (conhost default 120x30) through resizes.
// CONOUT$ always opens whichever buffer is currently active.
HANDLE activeBuffer = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, 0, nullptr);
const bool openedActiveBuffer = (activeBuffer != INVALID_HANDLE_VALUE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(openedActiveBuffer ? activeBuffer : GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
if (openedActiveBuffer)
{
CloseHandle(activeBuffer);
}
return std::pair<int, int>(csbi.srWindow.Right - csbi.srWindow.Left + 1,
csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
#elif defined(__linux__)
std::pair<int, int> get_screen_size() {
struct winsize size;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &size);
return std::pair<int, int>(size.ws_col, size.ws_row);
}
#endif
#if defined(_WIN32)
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 // missing from some older MinGW headers
#endif
namespace
{
/**
* @brief Writes a DECSCUSR cursor-shape escape sequence ("ESC [ n SP q") to the active console
* screen buffer. Windows Terminal (the Windows 11 default) draws its own cursor and
* ignores the console-API cursor size that curs_set() sets, but honors DECSCUSR, as
* does conhost on Windows 10+.
*
* Writes through CONOUT$ for the same reason as get_screen_size(): PDCurses draws into its own
* screen buffer. VT processing is enabled only for this one write and the buffer's original
* mode restored afterwards, so PDCurses' own output mode is left exactly as it was. If VT
* processing can't be enabled (pre-Windows 10 consoles), nothing is written, since the
* sequence would otherwise print as literal "[1 q" text.
*/
void writeCursorShapeSequence(const std::string & sequence)
{
HANDLE activeBuffer = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, 0, nullptr);
if(activeBuffer == INVALID_HANDLE_VALUE)
{
return;
}
DWORD originalMode = 0;
if(GetConsoleMode(activeBuffer, &originalMode)
&& SetConsoleMode(activeBuffer, originalMode | ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
DWORD written = 0;
WriteConsoleA(activeBuffer, sequence.c_str(), static_cast<DWORD>(sequence.size()), &written, nullptr);
SetConsoleMode(activeBuffer, originalMode);
}
CloseHandle(activeBuffer);
}
}
#endif
void hideCursor() { curs_set(0); }
void showCursor()
{
#if defined(_WIN32)
// PDCurses' wincon backend maps curs_set(1) ("normal") to the
// console's original/default cursor size (PDC_curs_set(), SP->
// orig_cursor), which on the standard Windows console is a thin
// underline - unlike Linux terminals, where a "normal" cursor
// typically fills the whole cell. curs_set(2) ("high visibility")
// maps to a 95%-of-cell-height block on wincon, matching Linux's
// appearance.
curs_set(2);
// Windows Terminal ignores the size curs_set() sets, so also request a
// blinking block directly. Sent after curs_set() so a console that maps
// the cursor-size call onto a shape can't override it.
writeCursorShapeSequence("\x1b[1 q");
#else
curs_set(1);
#endif
}
void restoreState()
{
#if defined(_WIN32)
// DECSCUSR 0 = the terminal's own default shape. Windows Terminal keeps
// the last requested shape after the program exits, so without this the
// player's shell would be left with showCursor()'s block cursor.
writeCursorShapeSequence("\x1b[0 q");
#endif
}
void curses_prepare_color()
{
if(has_colors())
{
start_color();
// Set up Curses color codes
Colors::curses_setup_colorCodes();
// Set up Curses colorpairs
Colors::curses_setup_colorPairs();
curses_colorCompatible = true;
textStyling = true;
}
else
{
curses_colorCompatible = false;
textStyling = false;
}
}
void setTerminalTitle(const std::string & title)
{
#if defined(_WIN32)
PDC_set_title(title.c_str());
#elif defined(__linux__)
std::cout << "\033]0;" << title << "\007" << std::flush;
#endif
}
void resizeTerminalWindow(int rows, int cols)
{
#if defined(_WIN32)
resize_term(rows, cols);
#endif
// No portable way to resize the user's terminal emulator window on
// Linux/macOS - intentionally a no-op there.
}
void enableTrueBlink()
{
#if defined(_WIN32)
// PDCursesMod defaults A_BLINK to setting the background to high
// intensity instead of actually blinking (PDC_set_blink(FALSE) is
// the default on most platforms, per pdcsetsc.c) - without this
// call, blink=true text just renders as a bright/light background
// and never flashes. Real terminals (Linux/macOS) already treat
// A_BLINK as a true blink via terminfo, so this is a no-op there.
PDC_set_blink(TRUE);
#endif
}
void initialize(bool initWindowManager,
const std::vector<std::string>& windowNames) {
// Initialize ncurses
initscr();
// Set up color support
curses_prepare_color();
// Configure ncurses behavior
cbreak(); // Disable line buffering
noecho(); // Don't echo input
keypad(stdscr, TRUE); // Enable function keys
curs_set(0); // Hide cursor
// Initialize window manager if requested
if (initWindowManager)
{
if (!windowNames.empty())
{
windowManager().initialize(windowNames);
}
else
{
windowManager().initialize(); // Use default windows
}
}
// Set display mode based on screen size
//setDisplayMode(get_screen_size());
}
void shutdown() {
windowManager().shutdown(); // This handles both window cleanup and endwin()
}
bool displayMode_GTEminSize(std::pair<int,int> minSize, std::pair<int,int> screenSize) {
if(minSize.first == -1 && minSize.second == -1) {
return true;
}
if(minSize.first == -1) {
return screenSize.second >= minSize.second;
}
if(minSize.second == -1) {
return screenSize.first >= minSize.first;
}
return (screenSize.first >= minSize.first && screenSize.second >= minSize.second);
}
bool displayMode_LTEmaxSize(std::pair<int,int> maxSize, std::pair<int,int> screenSize) {
if(maxSize.first == -1 && maxSize.second == -1) {
return true;
}
if(maxSize.first == -1) {
return screenSize.second <= maxSize.second;
}
if(maxSize.second == -1) {
return screenSize.first <= maxSize.first;
}
return (screenSize.first <= maxSize.first && screenSize.second <= maxSize.second);
}
void setDisplayMode(std::pair<int,int> screenSize) {
for(auto const& mode : displayModes) {
if(displayMode_GTEminSize(mode.second.minSize, screenSize) &&
displayMode_LTEmaxSize(mode.second.maxSize, screenSize)) {
currentDisplayMode = mode.first;
return;
}
}
// If no mode matches, default to "regular"
currentDisplayMode = "regular";
}
// ==================== COLORS.HPP IMPLEMENTATIONS ====================
namespace Colors {
std::unordered_map<std::string, int> curses_colorPairs;
std::unordered_map<std::string, int> curses_colors;
void curses_setup_colorCodes()
{
// First 2 colors
if(COLORS >= 2)
{
curses_colors["black"] = COLOR_BLACK;
curses_colors["white"] = COLOR_WHITE;
}
else
{
std::cout << "Error from stevensTerminal::Colors - less than 2 colors available for use detected! Closing program." << std::endl;
exit(EXIT_FAILURE);
}
// 8 colors
if(COLORS >= 8)
{
curses_colors["red"] = COLOR_RED;
curses_colors["green"] = COLOR_GREEN;
curses_colors["yellow"] = COLOR_YELLOW;
curses_colors["blue"] = COLOR_BLUE;
curses_colors["magenta"] = COLOR_MAGENTA;
curses_colors["cyan"] = COLOR_CYAN;
}
// 16 colors
// NOTE: computed from the base colors' own (already bit-order-correct)
// values rather than hardcoded absolute numbers. PDCurses' COLOR_RED/
// COLOR_BLUE/etc. resolve differently depending on whether PDC_RGB is
// defined (RGB vs. legacy PC BGR bit ordering) - hardcoding e.g.
// "bright-yellow = 11" silently assumed RGB ordering (yellow=3, +8=11),
// which is wrong under PDCursesMod's Windows default (BGR, where 11 is
// actually the bright-cyan slot) - this is exactly why yellow rendered
// as cyan and blue rendered as red on Windows.
if(COLORS >= 16)
{
curses_colors["bright-black"] = curses_colors["black"] + 8;
curses_colors["bright-red"] = curses_colors["red"] + 8;
curses_colors["bright-green"] = curses_colors["green"] + 8;
curses_colors["bright-yellow"] = curses_colors["yellow"] + 8;
curses_colors["bright-blue"] = curses_colors["blue"] + 8;
curses_colors["bright-magenta"] = curses_colors["magenta"] + 8;
curses_colors["bright-cyan"] = curses_colors["cyan"] + 8;
curses_colors["bright-white"] = curses_colors["white"] + 8;
}
}
void curses_setup_colorPairs()
{
// Error check
if ((COLORS < 2) || (COLOR_PAIRS < 1)) {
std::cout << "Error from stevensTerminal::Colors - insufficient color support! Closing program." << std::endl;
exit(EXIT_FAILURE);
}
// Get all available colors from curses_colors map
std::vector<int> allColors = stevensMapLib::getValueVector(curses_colors);
std::vector<std::string> allColorNames = stevensMapLib::getKeyVector(curses_colors);
int pairNum = 0;
// Generate all foreground x background combinations
for (size_t bgIdx = 0; bgIdx < allColors.size(); ++bgIdx) {
int bgColor = allColors[bgIdx];
const std::string& bgName = allColorNames[bgIdx];
// Skip bright backgrounds if we don't have 16 colors
if (bgColor >= 8 && COLORS < 16) continue;
for (size_t fgIdx = 0; fgIdx < allColors.size(); ++fgIdx) {
int fgColor = allColors[fgIdx];
const std::string& fgName = allColorNames[fgIdx];
// Skip bright foregrounds if we don't have 16 colors
if (fgColor >= 8 && COLORS < 16) continue;
// Skip if we've exceeded available color pairs
if (pairNum >= COLOR_PAIRS) break;
// Create the color pair
std::string pairName = fgName + "_on_" + bgName;
init_pair(pairNum, fgColor, bgColor);
curses_colorPairs[pairName] = pairNum;
// Special case: "default" for white on black
if (pairNum == 0) {
curses_colorPairs["default"] = pairNum;
}
pairNum++;
}
// Stop if we've exceeded available color pairs
if (pairNum >= COLOR_PAIRS) break;
}
}
std::string colorToString(int colorNum)
{
std::string result = stevensMapLib::getKeyByValue(curses_colors, colorNum);
// If not found (empty string), return "white" as fallback
return result.empty() ? "white" : result;
}
int lookupColorPair(int fgColor, int bgColor) {
std::string fgName = colorToString(fgColor);
std::string bgName = colorToString(bgColor);
std::string pairName = fgName + "_on_" + bgName;
if (curses_colorPairs.contains(pairName)) {
return curses_colorPairs[pairName];
}
// Fallback to pair 0 (default white on black)
return 0;
}
int lookupColorPairByName(const std::string& fgName, const std::string& bgName) {
std::string pairName = fgName + "_on_" + bgName;
if (curses_colorPairs.contains(pairName))
return curses_colorPairs.at(pairName);
return 0;
}
short extractForegroundColor(int colorPairNum) {
short fg, bg;
pair_content(colorPairNum, &fg, &bg);
return fg;
}
short extractBackgroundColor(int colorPairNum) {
short fg, bg;
pair_content(colorPairNum, &fg, &bg);
return bg;
}
} // namespace Colors
// ==================== STYLING.HPP IMPLEMENTATIONS ====================
std::string styleRandomTextColorPerCharacter(std::string str,
std::unordered_map<std::string,int> colorPool)
{
if(colorPool.empty())
{
colorPool = Colors::curses_colors;
colorPool.erase("black");
}
std::string result;
for(const std::string & codepoint : stevensStringLib::separate(str, ""))
{
result += style(codepoint, {{"textColor", stevensMapLib::getRandomKey(colorPool)}});
}
return result;
}
const std::unordered_map<std::string, std::function<std::string(const std::string&)>> styleMacros = {
{"randomTextColorPerCharacter", [](const std::string & str) { return styleRandomTextColorPerCharacter(str); }}
};
std::string style(std::string str,
std::unordered_map<std::string,std::string> styleMap)
{
// A style macro request takes over entirely - it names a code-driven styling procedure
// instead of literal key=value token attributes.
if(styleMap.contains(styleMacroKey))
{
auto macroIt = styleMacros.find(styleMap.at(styleMacroKey));
if(macroIt != styleMacros.end())
{
return macroIt->second(str);
}
spdlog::error("style(): unknown styleMacro requested: {}", styleMap.at(styleMacroKey));
}
// Read the contents of the style map into a std::string list of keys and values associated by '=' and delimited by ','
std::string styleString = stevensStringLib::stringifyMap(styleMap, "=", ",");
str = "{" + str + "}$[" + styleString + "]";
return str;
}
void insertStyleToken(std::string & str,
const PrintToken & token)
{
// First check to see if the index that the token exists at is valid
if( token.existsAtIndex >= str.length() ) {
// If not, just return without doing anything
return;
}
// Otherwise, begin by placing the left content bound character at the token's existsAtIndex
str.insert(token.existsAtIndex, 1, '{');
// To find the placement of the right content bound character, step over the length of the content from the existsAtIndex
size_t indexOfRightContentBound = token.existsAtIndex + token.content.length() + 1;
// If this would cause us to exceed the length of the string, just place the indexOfRightContentBound at the end of the std::string
if(indexOfRightContentBound >= str.length() ) {
indexOfRightContentBound = str.length();
}
// Get the directives to place in the style std::string
std::string styleString = token.getStyleString();
// Insert the right bound and the style directives
std::string endOfToken = "}$[" + styleString + "]";
str.insert(indexOfRightContentBound, endOfToken);
}
std::string removeAllStyleTokenization(std::string str)
{
// Find a token return its position in the std::string
size_t tokenPosition = PrintTokenHelper::findToken(str);
// If findToken return std::string::npos, then no token was found
while( tokenPosition != std::string::npos ) {
// Remove its braces and styling directives
str = PrintTokenHelper::untokenize(str, tokenPosition);
// Try to find the position of the next token
tokenPosition = PrintTokenHelper::findToken(str);
}
return str;
}
std::string resizeStyledString(std::string str, const size_t desiredLength, const char fillChar,
const std::string & truncationSuffix)
{
// Measure the display width of the plain content (all token markup stripped).
std::string contentString = removeAllStyleTokenization(str);
size_t currentWidth = stevensStringLib::lineDisplayWidth(contentString);
if (currentWidth == desiredLength)
{
return str;
}
if (currentWidth < desiredLength)
{
// Padding: append fill characters directly to the end of the styled string.
// This preserves all nested token structure intact — no strip-and-reinsert needed,
// so inner tokens (e.g. bright-green value inside a bright-yellow response line)
// survive and are correctly flattened later by tokenizePrintString/preprocessNestedTokens.
// truncationSuffix is ignored here -- it only ever applies to a cut, never a pad.
str.append(desiredLength - currentWidth, fillChar);
return str;
}
// Truncation path (currentWidth > desiredLength): strip tokens, truncate plain content,
// reinsert top-level tokens. Note: nested inner tokens lose their structure here because
// token.content may contain markup that isn't present in contentString; this is a
// pre-existing limitation of the strip-and-reinsert approach, and truncation with nested
// styled strings is rare in practice.
// If a truncation suffix was given, the plain content is truncated to
// (desiredLength - suffix length) instead, so the suffix still fits inside desiredLength --
// unless the suffix alone would be as long as desiredLength, in which case it's dropped and
// this falls back to plain truncation rather than emitting only the suffix (mirrors
// stevensStringLib::resizeToDisplayWidth's own suffix handling).
size_t truncateWidth = desiredLength;
std::string suffix;
if (!truncationSuffix.empty() && truncationSuffix.length() < desiredLength)
{
truncateWidth = desiredLength - truncationSuffix.length();
suffix = truncationSuffix;
}
// If there are no style tokens, just resize the plain content
std::vector<PrintToken> tokens = PrintTokenHelper::getAllTokens(str);
if (tokens.empty())
{
return stevensStringLib::resizeToCodepoints(contentString, truncateWidth, fillChar) + suffix;
}
// getAllTokens() reports each token's existsAtIndex as a byte position in the ORIGINAL
// (fully tokenized) string, but insertStyleToken() below needs each token's position within
// contentString (the token-stripped string) to reinsert it correctly. Adjust for the wrapper
// overhead ("{" + "}$[" + style + "]") of every earlier token, which contentString doesn't
// have - without this, only a single leading token's position is ever correct by coincidence;
// a second (or later) token's existsAtIndex is too large by the combined wrapper overhead of
// every token before it, so it gets reinserted at the wrong spot. Byte-based on purpose (see
// insertStyleToken()'s std::string::insert() calls below) - safe for multi-byte content because
// rawToken.length() - content.length() always cancels content's own length out, leaving just
// the (always-ASCII) markup's byte count, regardless of what content actually contains.
size_t wrapperOverhead = 0;
for (PrintToken & token : tokens)
{
token.existsAtIndex -= wrapperOverhead;
wrapperOverhead += token.rawToken.length() - token.content.length();
}
// We resize this std::string by codepoint, not byte, so multi-byte content (Cyrillic, CJK, etc.)
// isn't torn in half by truncation or padded to the wrong displayed width
contentString = stevensStringLib::resizeToCodepoints(contentString, truncateWidth, fillChar);
std::string resizedStr = contentString;
// We now place the style tokens back into this resized std::string. insertStyleToken() mutates
// resizedStr in place, growing it by each token's wrapper overhead - so every later token's
// existsAtIndex (already adjusted above to be correct against the original content-only string)
// also needs to account for the growth every earlier-in-this-loop insertion just added, or it
// lands wherever the string happened to be *before* those insertions instead of where the
// content actually ended up.
size_t reinsertionGrowth = 0;
for (int tokenIndex = 0; tokenIndex < (int)tokens.size(); tokenIndex++)
{
tokens.at(tokenIndex).existsAtIndex += reinsertionGrowth;
// For each style token, check to see if the index which it starts relative to the content and all other tokens
// is still in bounds of the string's length
if (tokens.at(tokenIndex).existsAtIndex + 1 < resizedStr.length())
{
// If so, then we add the style token back at its original location
insertStyleToken(resizedStr, tokens.at(tokenIndex));
reinsertionGrowth += tokens.at(tokenIndex).rawToken.length() - tokens.at(tokenIndex).content.length();
}
else
{
// Otherwise, all other style tokens will no longer be in bounds either, as they come after the current one
// in order, so we break and finish
break;
}
}
return resizedStr + suffix;
}
// NOTE: printHorizontalBorder() (plain std::cout ANSI-styling-era border
// printer) was removed — unreachable from anywhere in cultgame or elsewhere
// in this library. Use curses_wprint()-based rendering instead.
// ==================== INPUT.HPP IMPLEMENTATIONS ====================
void clearInput() {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// NOTE: the plain no-arg input() overload (std::cin/std::getline-based, from
// before the WINDOW*-based input() existed) was removed — unreachable from
// anywhere in cultgame or elsewhere in this library.
int input(int responseRange) {
if (responseRange < 0) {
// Handle error case for negative response range
void(0);
}
std::string userInput; // the input from the player
int userInputAsNum; // casted form of the user input
bool hasValidInput = false; // bool declaring whether or not the correct input has been received
while (hasValidInput == false) {
std::cout << "> ";
std::cin >> userInput;
if (stevensStringLib::isNumber(userInput)) {
hasValidInput = true;
userInputAsNum = stoi(userInput);
if (responseRange >= 0) { // we request that our integer response be within a certain range
if (!((userInputAsNum >= 0) && (userInputAsNum <= responseRange))) {
hasValidInput = false;
}
}
} else {
hasValidInput = false;
}
clearInput();
}
return userInputAsNum;
}
bool inputWithinResponseRange(std::string input, int responseRange) {
if(stevensStringLib::isNumber(input)) {
int inputAsInt = std::stoi(input);
if((inputAsInt >= 1) && (inputAsInt <= responseRange)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
std::string input(
WINDOW * win,
size_t maxLen,
const std::unordered_map<std::string,std::string> & textStyle
)
{
cbreak();
noecho();
keypad(win, true);
showCursor();
#if defined(__linux__)
// set_escdelay() is an ncurses extension (delay before treating a lone ESC
// as a keypress rather than the start of a function-key sequence). PDCurses
// has no equivalent and doesn't need one: the Win32 console API reports
// key events individually rather than as ambiguous escape sequences.
set_escdelay(25);
#endif
std::unordered_map<std::string,chtype> styleAttrs = PrintHelper::curses_styleAttributes(textStyle);
// Re-renders str into the window interior on each keystroke.
// Clears all inner rows first (eliminates color bleed from previously-rendered
// content), then prints str with textStyle, then positions the cursor at end.
// Grows the window by one row via wresize if the cursor would hit the bottom border.
auto renderInput = [&](const std::string & str)
{
int winHeight, winWidth;
getmaxyx(win, winHeight, winWidth);
const int innerWidth = winWidth - 2;
int cursorRow = 1 + static_cast<int>(str.size()) / innerWidth;
if(cursorRow >= winHeight - 1)
{
wresize(win, winHeight + 1, winWidth);
getmaxyx(win, winHeight, winWidth);
}
wattrset(win, A_NORMAL);
for(int r = 1; r < winHeight - 1; r++)
{
wmove(win, r, 1);
for(int c = 0; c < innerWidth; c++)
waddch(win, ' ');
}
PrintHelper::curses_wAttrOn(win, styleAttrs);
for(size_t i = 0; i < str.size(); i++)
{
int r = 1 + static_cast<int>(i) / innerWidth;
int c = 1 + static_cast<int>(i) % innerWidth;
wmove(win, r, c);
waddch(win, str[i]);
}
PrintHelper::curses_wAttrOff(win, styleAttrs);
int cursorCol = 1 + static_cast<int>(str.size()) % innerWidth;
wmove(win, cursorRow, cursorCol);
wrefresh(win);
};
std::string str = "";
bool escaped = false;
renderInput(str);
while(true)
{
int ch = wgetch(win);
std::string inputChar(1, static_cast<char>(ch));
if(inputChar == key::Esc)
{
escaped = true;
break;
}
if(ch == '\n' || ch == '\r' || ch == KEY_ENTER)
break;
if(ch == KEY_BACKSPACE || ch == 127 || ch == 8)
{
if(!str.empty())
{
str.pop_back();
renderInput(str);
}
continue;
}
if(ch >= 32 && ch < 127 && str.size() < maxLen)
{
str.push_back(static_cast<char>(ch));
renderInput(str);
}
}
keypad(win, false);
hideCursor();
if(escaped)
return key::Esc;
return str;
}
// ==================== PARTICLEFX IMPLEMENTATIONS ====================
namespace ParticleFX {
// Static member definition for ParticleWindowRegistry
std::unordered_map<WINDOW*, ParticleWindowRegistry::WindowState> ParticleWindowRegistry::registry;
} // namespace ParticleFX
} // namespace stevensTerminal
namespace stevensTerminal
{
// ==================== FUNCTIONS MOVED FROM HEADER ====================
// (previously defined inline in stevensTerminal.hpp)
// ==================== calculateBarGraphLabel ====================
BarGraphLabelFormat calculateBarGraphLabel(
const std::string& labelText,
float percentage,
int availableWidth,
bool showText,
bool showPercentage)
{
BarGraphLabelFormat result;
result.style = BarGraphLabelStyle::None;
result.text = "";
result.width = 0;
result.indent = 0;
if (!showText && !showPercentage) {
return result;
}
std::string percentageStr = std::to_string(stevensMathLib::roundToNearest10th(percentage * 100));
// Try text + percentage first (most informative)
if (showText && showPercentage) {
std::string combined = labelText + " " + percentageStr + "%";
if (static_cast<int>(combined.length()) <= availableWidth) {
result.text = combined;
result.style = BarGraphLabelStyle::TextAndPercentage;
result.width = combined.length();
result.indent = (availableWidth - result.width) / 2;
return result;
}
}
// Try percentage only (compact)
if (showPercentage) {
std::string percentageLabel = percentageStr + "%";
if (static_cast<int>(percentageLabel.length()) <= availableWidth) {
result.text = percentageLabel;
result.style = BarGraphLabelStyle::PercentageOnly;
result.width = percentageLabel.length();
result.indent = (availableWidth - result.width) / 2;
return result;
}
}
// Try text only
if (showText && static_cast<int>(labelText.length()) <= availableWidth) {
result.text = labelText;
result.style = BarGraphLabelStyle::TextOnly;
result.width = labelText.length();
result.indent = (availableWidth - result.width) / 2;
return result;
}
// Nothing fits - return empty
return result;
}
// ==================== horizontalStackedBarGraph ====================
void horizontalStackedBarGraph( std::vector<std::string> labels,
std::vector< std::tuple<std::string,std::string> > colorCombos,
std::vector<float> distribution,
int width,
bool textLabels,
bool percentageLabels )
{
// Input validation
if(labels.size() != colorCombos.size() || labels.size() != distribution.size())
{
std::cerr << "Error: horizontalStackedBarGraph requires labels, colorCombos, and distribution vectors to have equal sizes" << std::endl;
return;
}
if(width <= 0)
{
std::cerr << "Error: horizontalStackedBarGraph width must be positive" << std::endl;
return;
}
if(labels.empty())
{
return; // Nothing to graph
}
if(!textStyling)
{
return; // Styling must be enabled for colored graphs
}
// Calculate total distribution
float sumOfDistributions = 0;
for(size_t labelIndex = 0; labelIndex < labels.size(); labelIndex++)
{
sumOfDistributions += distribution[labelIndex];
}
// Guard against division by zero
if(sumOfDistributions == 0)
{
return; // Cannot create bar graph with zero total distribution
}
// Calculate percentages for each label
std::vector<float> distributionPercentages;
distributionPercentages.reserve(labels.size());
for(size_t labelIndex = 0; labelIndex < labels.size(); labelIndex++)
{
distributionPercentages.push_back(distribution[labelIndex] / sumOfDistributions);
}
// Calculate bar width for each segment (in characters)
std::vector<int> segmentWidths;
segmentWidths.reserve(labels.size());
for(size_t labelIndex = 0; labelIndex < labels.size(); labelIndex++)
{
int segmentWidth = static_cast<int>(floor(distributionPercentages[labelIndex] * width));
segmentWidths.push_back(segmentWidth);
}
// Render each bar segment
for(size_t labelIndex = 0; labelIndex < labels.size(); labelIndex++)
{
// Calculate optimal label for this segment
BarGraphLabelFormat labelFormat = calculateBarGraphLabel(
labels[labelIndex],
distributionPercentages[labelIndex],
segmentWidths[labelIndex],
textLabels,
percentageLabels
);
// Get colors for this segment
const std::string& bgColor = std::get<0>(colorCombos[labelIndex]);
const std::string& textColor = std::get<1>(colorCombos[labelIndex]);
// Print the segment character by character
int charsRemaining = segmentWidths[labelIndex];
int indentRemaining = labelFormat.indent;
size_t labelCharIndex = 0;
while(charsRemaining > 0)
{
// // Print indent spaces first
// if(indentRemaining > 0)
// {
// print(" ", {{"textColor", textColor}, {"bgColor", bgColor}});
// indentRemaining--;
// }
// // Then print label characters
// else if(labelCharIndex < labelFormat.text.length())
// {
// std::string charAsString(1, labelFormat.text[labelCharIndex]);
// print(charAsString, {{"textColor", textColor}, {"bgColor", bgColor}, {"bold", "true"}});
// labelCharIndex++;
// }
// // Fill remaining space
// else
// {
// print(" ", {{"textColor", textColor}, {"bgColor", bgColor}});
// }
charsRemaining--;
}
}
std::cout << "\n";
}
// NOTE: table() (plain std::cout ANSI-styling-era table printer) was removed
// — unreachable from anywhere in cultgame or elsewhere in this library.
// NOTE: localizedWrap(), increaseOffset(), verticalMenus(), and
// promptMultipleResponses() (plain std::cout ANSI-styling-era menu/response
// printers) were removed — unreachable from anywhere in cultgame or elsewhere
// in this library (verticalMenus is only ever referenced in README examples).
// ==================== curses_wprint ====================
void curses_wprint( WINDOW * win,
int yMove,
int xMove,
std::string printString,
std::unordered_map<std::string,std::string> style,
std::unordered_map<std::string,std::string> format )
{
PrintHelper::curses_wprint( win,
yMove,
xMove,
printString,
style,
format,
textStyling );
}
// ==================== getWrapWidth ====================
int getWrapWidth(int windowWidth, const std::unordered_map<std::string,std::string> & format)
{
return PrintHelper::getWrapWidth(windowWidth, format);
}
// ==================== countWrappedLines ====================
int countWrappedLines(const std::string & text, int windowWidth, const std::unordered_map<std::string,std::string> & format)
{
if(text.empty())
{
return 0;
}
int wrapWidth = getWrapWidth(windowWidth, format);
// Same indent rule curses_wwrap_withTokens() applies: the first row gets the full width,
// every row after it (wrapped or after an explicit newline) loses subsequentIndent columns.
int subsequentIndent = PrintHelper::getSubsequentIndent(format, wrapWidth);
std::string wrapped = stevensStringLib::wrapToWidth( removeAllStyleTokenization(text),
wrapWidth - subsequentIndent,
wrapWidth );
return stevensStringLib::countLines(wrapped);
}
// ==================== curses_wprintDirect ====================
void curses_wprintDirect( WINDOW * win,
int yMove,
int xMove,
const std::string & printString,
const std::unordered_map<std::string,std::string> & style )
{
std::unordered_map<std::string, chtype> attrs = PrintHelper::curses_styleAttributes(style);
PrintHelper::curses_wAttrOn(win, attrs);
mvwaddstr(win, yMove, xMove, printString.c_str());
PrintHelper::curses_wAttrOff(win, attrs);
}
// ==================== curses_wGetAttrs ====================