-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoNameOS.cpp
More file actions
4928 lines (4669 loc) · 235 KB
/
Copy pathNoNameOS.cpp
File metadata and controls
4928 lines (4669 loc) · 235 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
// This is... _ __ _ __ ____ _____
// / | / /___ / | / /___ _____ ___ ___ / __ \/ ___/
// / |/ / __ \/ |/ / __ `/ __ `__ \/ _ \/ / / /\__ \
// / /| / /_/ / /| / /_/ / / / / / / __/ /_/ /___/ /
// /_/ |_/\____/_/ |_/\__,_/_/ /_/ /_/\___/\____//____/ ...The pure C++ Terminal OS simulation works in almost all OSes some usked for...
// ══════════════════════════════════════════════════════════════════════════════
// NoNameOS - A pure C++ hobbyist operating-system simulation
// ══════════════════════════════════════════════════════════════════════════════
// Single-file C++ project (~4900 lines) featuring:
// - Interactive shell with color-coded prompt, arrow key support, history
// - Virtual filesystem (VFS) with files, directories, symlinks, permissions
// - 24+ built-in games (Snake, Tetris, Sudoku, Pong, 2048, etc.)
// - 135+ commands (text tools, converters, math, productivity, fun)
// - 256-color ANSI visuals with animated boot logo
// - 25+ hidden easter eggs
//
// Build: g++ -O3 NoNameOS.cpp -o nonameos
// Run: ./nonameos
// License: GPLv3
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 1: Includes, Constants, and Utility Functions
// ══════════════════════════════════════════════════════════════════════════════
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <csignal>
#include <algorithm>
#include <sstream>
#include <random>
#include <functional>
#include <optional>
#include <iomanip>
#include <cstring>
#include <climits>
#include <array>
// POSIX headers for terminal control (raw input) and non-blocking I/O detection
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 2: Signal Handling and Terminal State Management
// ══════════════════════════════════════════════════════════════════════════════
// SIGINT handler exits cleanly — the shell restores terminal state on process exit.
// tcsetattr() is NOT async-signal-safe, so we must not call it here.
static struct termios g_orig_term;
static volatile sig_atomic_t g_term_saved = 0;
static void sigint_handler(int) {
_exit(1);
}
static const auto program_start = chrono::steady_clock::now();
const string VERSION = "v1.0.2";
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 3: ANSI Color System and Visual Helpers
// ══════════════════════════════════════════════════════════════════════════════
// 256-color and truecolor ANSI escape code wrappers for terminal coloring
namespace clr {
// 256-color foreground
inline string fg256(int c) { return "\033[38;5;" + to_string(c) + "m"; }
// Truecolor foreground
inline string rgb(int r, int g, int b) { return "\033[38;2;" + to_string(r) + ";" + to_string(g) + ";" + to_string(b) + "m"; }
// Truecolor background
inline string rgbbg(int r, int g, int b) { return "\033[48;2;" + to_string(r) + ";" + to_string(g) + ";" + to_string(b) + "m"; }
const string reset = "\033[0m";
const string bold = "\033[1m";
const string dim = "\033[2m";
const string italic = "\033[3m";
const string underline = "\033[4m";
const string blink = "\033[5m";
const string inverse = "\033[7m";
// Named colors (256)
const string red = fg256(196);
const string lred = fg256(203);
const string green = fg256(46);
const string lgreen = fg256(120);
const string yellow = fg256(226);
const string amber = fg256(214);
const string blue = fg256(39);
const string lblue = fg256(117);
const string cyan = fg256(51);
const string lcyan = fg256(123);
const string magenta = fg256(201);
const string lmagenta= fg256(207);
const string orange = fg256(208);
const string white = fg256(231);
const string gray = fg256(245);
const string dgray = fg256(240);
const string black = fg256(16);
// Semantic
const string success = bold + fg256(46);
const string error = bold + fg256(196);
const string warning = bold + fg256(226);
const string info = bold + fg256(39);
const string accent = bold + fg256(213);
const string muted = fg256(245);
const string header = bold + fg256(75);
const string prompt_user = bold + fg256(46);
const string prompt_host = fg256(231);
const string prompt_dir = fg256(39);
const string prompt_sep = fg256(240);
}
// --- Visual helpers ---
// Simple line separator
string vsep(int width, const string& ch = "─") {
string s;
for (int i = 0; i < width; i++) s += ch;
return s;
}
// Repeat a unicode character N times
string repeat(int n, const string& ch) {
string s;
for (int i = 0; i < n; i++) s += ch;
return s;
}
// --- Pseudo-random engine (replaces weak srand/rand) ---
static mt19937& rng() {
static mt19937 gen(random_device{}());
return gen;
}
static int rng_int(int lo, int hi) {
uniform_int_distribution<int> dist(lo, hi);
return dist(rng());
}
// --- Named constants (replaces magic numbers) ---
constexpr int GAME_SPEED_MS = 150;
constexpr int SNAKE_W = 20;
constexpr int SNAKE_H = 15;
constexpr int MINESWEEPER_W = 10;
constexpr int MINESWEEPER_H = 10;
constexpr int MINESWEEPER_MINES = 12;
constexpr int TTT_BOARD_CELLS = 9;
constexpr int HANGMAN_ATTEMPTS = 6;
constexpr int RPS_WIN_TARGET = 4;
constexpr int SLEEP_MAX_SEC = 30;
constexpr int YES_COUNT = 100;
constexpr int HEAD_TAIL_LINES = 10;
constexpr int TRIVIA_COUNT = 5;
constexpr int ASCIIDASH_PADDING = 10;
constexpr int ASCIIDASH_WINDOW = 20;
constexpr int JUMP_FRAMES = 3;
constexpr int WATCH_ITERATIONS = 5;
constexpr int PING_COUNT = 4;
constexpr int TRAIN_START_OFFSET = 50;
constexpr int TRAIN_END_OFFSET = -40;
constexpr int TRAIN_FRAME_MS = 80;
// New game constants
constexpr int TETRIS_W = 10;
constexpr int TETRIS_H = 20;
constexpr int PONG_W = 40;
constexpr int PONG_H = 15;
constexpr int FLAPPY_W = 30;
constexpr int FLAPPY_H = 15;
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 4: Core Data Structures (FSNode, TerminalGuard, Question)
// ══════════════════════════════════════════════════════════════════════════════
// FSNode: Virtual filesystem node (file/directory/symlink)
// TerminalGuard: RAII wrapper for raw terminal mode (auto-restores on destruction)
// Question: Trivia quiz question with options and correct answer index
struct Question {
string q;
vector<string> opts;
int correct = 0;
};
struct TerminalGuard {
struct termios oldt;
int oldf;
bool active = false;
TerminalGuard() {
active = (tcgetattr(STDIN_FILENO, &oldt) == 0);
if (active) {
g_orig_term = oldt;
g_term_saved = 1;
struct termios newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
}
}
~TerminalGuard() {
if (active) {
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
g_term_saved = 0;
}
}
TerminalGuard(const TerminalGuard&) = delete;
TerminalGuard& operator=(const TerminalGuard&) = delete;
};
// Generate a human-readable timestamp string (e.g. "Jul 05 09:53") for VFS metadata
string get_timestamp() {
time_t now = time(nullptr);
tm t_buf;
localtime_r(&now, &t_buf);
char buf[20];
strftime(buf, sizeof(buf), "%b %d %H:%M", &t_buf);
return string(buf);
}
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 5: Virtual Filesystem (VFS) Implementation
// ══════════════════════════════════════════════════════════════════════════════
// FSNode represents a file, directory, or symlink in the in-memory VFS
// resolved_path follows symlink chains (max 8 deep to prevent cycles)
// vfs_read returns file content as optional<string> (nullopt if not found)
string cooked_readline();
struct FSNode {
bool is_dir;
bool is_link;
string content;
string created_at;
string mode;
string link_target;
FSNode() : is_dir(false), is_link(false), content(""), created_at(""), mode("rw-r--r--"), link_target("") {}
FSNode(bool d, string c) : is_dir(d), is_link(false), content(c), created_at(get_timestamp()),
mode(d ? "rwxr-xr-x" : "rw-r--r--"), link_target("") {}
size_t size() const { return content.size(); }
};
string resolved_path(map<string,FSNode>& fs, const string& path, int depth = 0) {
if (depth > 8) return path;
if (fs.find(path) != fs.end() && fs[path].is_link)
return resolved_path(fs, fs[path].link_target, depth + 1);
return path;
}
string help_text(const string& cmd) {
static const map<string,string> ht = {
{"help","show help or describe a command"},{"man","display manual page"},
{"ls","list directory contents"},{"cd","change directory"},
{"mkdir","create directory"},{"touch","create empty file"},
{"cat","print file contents"},{"echo","write content to file"},
{"rm","remove file or directory"},{"cp","copy file"},
{"mv","move or rename"},{"clear","clear screen"},
{"exit","exit NoNameOS"},{"pwd","print working directory"},
{"whoami","print current user"},{"date","print date and time"},
{"history","show command history"},{"grep","search file for pattern"},
{"find","find files by name"},{"locate","find files by pattern"},
{"cfetch","system info"},{"ps","process list"},
{"uname","system information"},{"uptime","system uptime"},
{"cal","calendar"},{"rainbow","rainbow text"},
{"yes","repeat text"},{"env","environment variables"},
{"hostname","print hostname"},{"sleep","delay execution"},
{"which","locate command"},{"alias","manage aliases"},
{"unalias","remove alias"},{"users","list users"},
{"banner","ASCII banner"},{"fortune","random quote"},
{"factor","factorize number"},{"shuf","shuffle text"},
{"head","first 10 lines"},{"tail","last 10 lines"},
{"sort","sort lines"},{"wc","count lines/words/chars"},
{"tee","write and display"},{"nano","line editor"},
{"calc","calculator"},{"bc","better calculator"},
{"play","AsciiDash game"},{"guess","number guessing game"},
{"trivia","trivia quiz"},{"adventure","dungeon RPG"},
{"snake","snake game"},{"minesweeper","minesweeper"},
{"tictactoe","tic-tac-toe vs AI"},{"ttt","tic-tac-toe shortcut"},
{"hangman","hangman game"},{"rps","rock paper scissors"},
{"2048","2048 puzzle"},{"typing","typing speed test"},
{"reaction","reaction time test"},{"nummem","number memory game"},
{"tree","directory tree"},{"watch","run command repeatedly"},
{"ping","simulated ping"},{"top","process snapshot"},
{"df","VFS disk usage"},{"seq","print number sequence"},
{"printenv","print environment"},{"todo","task manager"},
{"notes","note manager"},{"stopwatch","stopwatch"},
{"timer","countdown timer"},{"lolcat","rainbow gradient text"},
{"cowsay","ASCII cow"},{"sl","steam locomotive"},
{"train","steam locomotive"},{"su","switch user"},
{"chmod","change permissions"},{"who","show logged in users"},
{"useradd","add user"},{"userdel","remove user"},
{"rev","reverse each line"},{"tr","replace characters"},
{"cut","extract first N chars"},{"paste","merge files"},
{"uniq","remove duplicate lines"},{"nl","number lines"},
{"fold","wrap lines"},{"basename","strip directory"},
{"dirname","extract directory"},{"free","memory usage"},
{"dmesg","boot messages"},{"lscpu","CPU info"},
{"lsusb","USB devices"},{"arch","print architecture"},
{"nproc","number of CPUs"},{"ln","create symlink"},
{"trash","manage trash"},{"du","disk usage"},
{"pom","pomodoro timer"},{"alarm","set alarm"}
};
auto it = ht.find(cmd);
return it != ht.end() ? it->second : "no description";
}
void boot_delay(int ms) {
this_thread::sleep_for(chrono::milliseconds(ms));
}
// Split raw input into a command token and its arguments string
pair<string, string> parse_command(const string& input) {
size_t first_space = input.find(' ');
if (first_space == string::npos) return {input, ""};
string args = input.substr(first_space + 1);
// Strip surrounding quotes from args (e.g. "Hi" → Hi)
if (args.size() >= 2 && args.front() == '"' && args.back() == '"')
args = args.substr(1, args.size() - 2);
return {input.substr(0, first_space), args};
}
// Resolve a user-provided path to an absolute VFS path, handling .. and absolute/relative
string resolve_user_path(const string& arg, const string& current_dir) {
string path;
if (!arg.empty() && arg[0] == '/') {
path = arg;
} else {
string cdir = current_dir;
if (!cdir.empty() && cdir.back() != '/') cdir += "/";
path = cdir + arg;
}
// Normalize: collapse /./ and handle /../
vector<string> parts;
istringstream ss(path);
string part;
while (getline(ss, part, '/')) {
if (part.empty() || part == ".") continue;
if (part == "..") {
if (!parts.empty()) parts.pop_back();
} else {
parts.push_back(part);
}
}
string result = "/";
for (size_t i = 0; i < parts.size(); i++) {
result += parts[i];
result += "/";
}
if (parts.empty()) result = "/";
return result;
}
// Check if a path or any component contains path-traversal sequences
bool has_traversal(const string& path) {
size_t start = 0;
while (start < path.size()) {
size_t pos = path.find('/', start);
string comp = path.substr(start, pos - start);
if (comp == "..") return true;
start = (pos == string::npos) ? path.size() : pos + 1;
}
return false;
}
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 6: Input Handling (kbhit, getkey, readline_global)
// ══════════════════════════════════════════════════════════════════════════════
// kbhit: non-blocking key detection using static peek buffer
// getkey: reads keys including arrow escape sequences (ESC [ A/B/C/D)
// readline_global: full readline with cursor movement, history, backspace
static int peek_buf = EOF;
int kbhit() {
if (peek_buf != EOF) return 1;
int ch = getchar();
if (ch != EOF) {
peek_buf = ch;
return 1;
}
return 0;
}
// Key codes for arrow keys
enum Key { KEY_NONE=0, KEY_UP=1000, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER, KEY_SPACE, KEY_Q, KEY_ESC };
// Read a key, handling escape sequences for arrow keys
// Returns the raw char for normal keys, or KEY_UP/DOWN/LEFT/RIGHT for arrows
int getkey() {
auto read_ch = []() -> int {
if (peek_buf != EOF) { int ch = peek_buf; peek_buf = EOF; return ch; }
return getchar();
};
int ch = read_ch();
if (ch == EOF) return KEY_NONE;
if (ch == 27) { // ESC
int ch2 = read_ch();
if (ch2 == EOF || ch2 == 27) return KEY_ESC; // bare ESC
if (ch2 == '[') {
// Wait briefly for the final byte of escape sequence
for (int retry = 0; retry < 5; retry++) {
int ch3 = read_ch();
if (ch3 != EOF) {
if (ch3 == 'A') return KEY_UP;
if (ch3 == 'B') return KEY_DOWN;
if (ch3 == 'C') return KEY_RIGHT;
if (ch3 == 'D') return KEY_LEFT;
return KEY_NONE;
}
this_thread::sleep_for(chrono::milliseconds(5));
}
return KEY_NONE;
}
return KEY_ESC;
}
if (ch == '\n' || ch == '\r') return KEY_ENTER;
if (ch == ' ') return KEY_SPACE;
return ch;
}
// Global readline with arrow key support for history navigation
// NOTE: Only supports ASCII input (k >= 32 && k < 127). UTF-8 in history will misposition the cursor.
string readline_global(const vector<string>& history) {
string line;
size_t cursor = 0;
int hist_idx = (int)history.size();
string saved;
auto redraw_from = [&]() {
cout << "\033[2K\r❯ " << line << flush;
cout << "\r\033[" << (cursor + 2) << "C" << flush;
};
while (true) {
int k = getkey();
if (k == KEY_NONE) {
this_thread::sleep_for(chrono::milliseconds(1));
continue;
}
if (k == KEY_ENTER) {
cout << "\n";
return line;
}
else if (k == KEY_UP) {
if (hist_idx > 0) {
if (hist_idx == (int)history.size()) saved = line;
hist_idx--;
line = history[hist_idx];
cursor = line.size();
redraw_from();
}
}
else if (k == KEY_DOWN) {
if (hist_idx < (int)history.size()) {
hist_idx++;
line = (hist_idx == (int)history.size()) ? saved : history[hist_idx];
cursor = line.size();
redraw_from();
}
}
else if (k == KEY_LEFT) {
if (cursor > 0) {
cursor--;
cout << "\033[D" << flush;
}
}
else if (k == KEY_RIGHT) {
if (cursor < line.size()) {
cursor++;
cout << "\033[C" << flush;
}
}
else if (k == 127 || k == 8) { // Backspace
if (cursor > 0) {
line.erase(cursor - 1, 1);
cursor--;
redraw_from();
}
}
else if (k == KEY_SPACE || (k >= 32 && k < 127)) { // Printable
line.insert(line.begin() + (int)cursor, k == KEY_SPACE ? ' ' : (char)k);
cursor++;
redraw_from();
}
}
}
optional<string> vfs_read(const string& path, map<string,FSNode>& fs, const string& cdir) {
string fp = resolve_user_path(path, cdir);
fp = resolved_path(fs, fp);
if (fs.find(fp) != fs.end() && !fs[fp].is_dir) return fs[fp].content;
return nullopt;
}
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 6.5: Cooked Mode Helper for getline-based input
// ══════════════════════════════════════════════════════════════════════════════
// Temporarily restores cooked terminal mode for getline calls, then re-enables raw mode
// This allows games using getline to echo typed characters properly
string cooked_readline() {
struct termios raw_t;
tcgetattr(STDIN_FILENO, &raw_t);
int old_flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, old_flags & ~O_NONBLOCK);
tcsetattr(STDIN_FILENO, TCSANOW, &g_orig_term);
string line;
getline(cin, line);
cin.clear();
fcntl(STDIN_FILENO, F_SETFL, old_flags);
struct termios raw2 = g_orig_term;
raw2.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &raw2);
return line;
}
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 7: Command Database and Fuzzy Matching
// ══════════════════════════════════════════════════════════════════════════════
// ALL_COMMANDS: Set of valid command names for validation and fuzzy matching
// edit_dist: Levenshtein distance for "did you mean?" suggestions
// closest_cmd: Finds the nearest valid command for typo correction
const set<string> ALL_COMMANDS = {"ls","cd","mkdir","touch","cat","echo","rm","clear","exit","play","cowsay",
"pwd","whoami","date","history","grep","find","cfetch","ps","uname","uptime","cal","rainbow",
"man","help","nano","calc","guess","trivia","adventure","snake","minesweeper","tictactoe","ttt",
"hangman","rps","yes","env","hostname","sleep","which","head","tail","sort","wc","tee","alias",
"users","banner","fortune","factor","shuf","cp","mv","chmod","su","unalias","tree","watch",
"ping","top","df","seq","printenv","todo","notes","stopwatch","timer","lolcat","sl",
"train","who","useradd","userdel","2048","typing","reaction","nummem","rev","tr","cut",
"paste","uniq","nl","fold","basename","dirname","free","dmesg","lscpu","lsusb","arch",
"nproc","du","locate","pom","alarm","bc","ln","trash",
"tetris","pong","sudoku","flappy","memory","connect4","lightsout","puzzle","breakout","whack",
"colors","weather","epoch","uuid","base64","rot13","uppercase","lowercase",
"wordcount","matrix","cmtheme","countdown","ascii","hexdump","password",
"quote","joke","ip","uptime2","mem","cpu","disk","calc2",
"bmi","tip","units","roman","binary","morse","bar","sparkline",
"colorgen","palette","diff","csv","stats","age","datecalc","encode",
"hash","djb2","md5","sha1","urlencode","urldecode","reverse","capitalize",
"repeat","scrabble","zodiac","chinese","emoji","random","pick","dice",
"coin","timer2","pom2","worldclock","stopwatch2","quiz","wordle",
"sudo","sandwich","42","meaning","life","konami","hack","hacker",
"rickroll","rick","beep","bell","yes-master","yes-sir",
"glhf","gg","lenny","shrug","tableflip","unflip","dealwithit",
"disco","dance","loading","wait",
"version","sudo-make-sandwich","open"};
size_t edit_dist(const string& a, const string& b) {
size_t n = a.size(), m = b.size();
vector<size_t> prev(m + 1), cur(m + 1);
for (size_t j = 0; j <= m; j++) prev[j] = j;
for (size_t i = 1; i <= n; i++) {
cur[0] = i;
for (size_t j = 1; j <= m; j++)
cur[j] = min({prev[j] + 1, cur[j-1] + 1, prev[j-1] + (a[i-1] == b[j-1] ? 0 : 1)});
swap(prev, cur);
}
return prev[m];
}
string closest_cmd(const string& cmd) {
string best; size_t best_d = 4;
for (const auto& c : ALL_COMMANDS) {
size_t d = edit_dist(cmd, c);
if (d < best_d) { best_d = d; best = c; }
}
return best;
}
// --- TEXT PROCESSING TOOLS ---
void cmd_rev(const string& args, map<string,FSNode>& fs, const string& cdir) {
if (args.empty()) { cout << "Usage: rev <file>\n"; return; }
auto c = vfs_read(args, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
istringstream ss(*c); string line;
while (getline(ss, line)) { reverse(line.begin(), line.end()); cout << line << "\n"; }
}
void cmd_tr(const string& args, map<string,FSNode>& fs, const string& cdir) {
istringstream ss(args); string fn, f, r;
ss >> fn >> f >> r;
if (fn.empty() || f.empty() || r.empty()) { cout << "Usage: tr <file> <find> <replace>\n"; return; }
auto c = vfs_read(fn, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
string content = *c;
// Map each find char to its corresponding replace char (cycle replace if shorter)
for (char& ch : content) {
for (size_t i = 0; i < f.size(); i++) {
if (ch == f[i]) { ch = r[i % r.size()]; break; }
}
}
cout << content << "\n";
}
void cmd_cut(const string& args, map<string,FSNode>& fs, const string& cdir) {
istringstream ss(args); string fn; int n;
ss >> fn >> n;
if (fn.empty() || n <= 0) { cout << "Usage: cut <file> <n>\n"; return; }
auto c = vfs_read(fn, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
istringstream is(*c); string line;
while (getline(is, line)) cout << line.substr(0, (size_t)n) << "\n";
}
void cmd_paste(const string& args, map<string,FSNode>& fs, const string& cdir) {
istringstream ss(args); string f1, f2;
ss >> f1 >> f2;
if (f1.empty() || f2.empty()) { cout << "Usage: paste <file1> <file2>\n"; return; }
auto c1 = vfs_read(f1, fs, cdir), c2 = vfs_read(f2, fs, cdir);
if (!c1 || !c2) { cout << "error: file not found.\n"; return; }
vector<string> l1, l2; string line;
{ istringstream s1(*c1); while (getline(s1, line)) l1.push_back(line); }
{ istringstream s2(*c2); while (getline(s2, line)) l2.push_back(line); }
for (size_t i = 0; i < max(l1.size(), l2.size()); i++) {
if (i < l1.size()) cout << l1[i]; cout << "\t";
if (i < l2.size()) cout << l2[i]; cout << "\n";
}
}
void cmd_uniq(const string& args, map<string,FSNode>& fs, const string& cdir) {
if (args.empty()) { cout << "Usage: uniq <file>\n"; return; }
auto c = vfs_read(args, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
istringstream ss(*c); string line, prev;
while (getline(ss, line)) { if (line != prev) cout << line << "\n"; prev = line; }
}
void cmd_nl(const string& args, map<string,FSNode>& fs, const string& cdir) {
if (args.empty()) { cout << "Usage: nl <file>\n"; return; }
auto c = vfs_read(args, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
istringstream ss(*c); string line; int n = 1;
while (getline(ss, line)) { cout << " " << n << "\t" << line << "\n"; n++; }
}
void cmd_fold(const string& args, map<string,FSNode>& fs, const string& cdir) {
istringstream ss(args); string fn; int n = 80;
ss >> fn >> n;
if (fn.empty()) { cout << "Usage: fold <file> [width]\n"; return; }
if (n <= 0) { cout << "error: width must be > 0.\n"; return; }
auto c = vfs_read(fn, fs, cdir);
if (!c) { cout << "error: file not found.\n"; return; }
for (size_t i = 0; i < c->length(); i += (size_t)n) cout << c->substr(i, (size_t)n) << "\n";
}
void cmd_basename(const string& args) {
if (args.empty()) { cout << "Usage: basename <path>\n"; return; }
size_t pos = args.find_last_of('/');
if (pos == string::npos) cout << args << "\n";
else if (pos == 0 && args.size() == 1) cout << "/\n";
else cout << args.substr(pos + 1) << "\n";
}
void cmd_dirname(const string& args) {
if (args.empty()) { cout << "Usage: dirname <path>\n"; return; }
size_t pos = args.find_last_of('/');
if (pos == string::npos) cout << ".\n";
else if (pos == 0) cout << "/\n";
else cout << args.substr(0, pos) << "\n";
}
// --- SYSTEM TOOLS ---
void cmd_free() {
cout << "\n " << clr::bold << clr::gray << " total used free shared buff/cache available" << clr::reset << "\n";
cout << " " << clr::dgray << " ─────────── ─────────── ─────────── ─────────── ─────────── ───────────" << clr::reset << "\n";
cout << " " << clr::white << "Mem: " << clr::lcyan << " 32768 18234 14534" << clr::gray << " 0 0 14534" << clr::reset << "\n";
cout << " " << clr::white << "Swap: " << clr::lcyan << " 8192 234 7958" << clr::reset << "\n\n";
}
void cmd_dmesg() {
struct msg { string ts; string level; string text; };
vector<msg> msgs = {
{"0.000000", "info", "NoNameOS " + VERSION + " booting on x86_64"},
{"0.102304", "info", "CPU: NoNameCPU v1.0 @ 2.4GHz (4 cores)"},
{"1.500000", "info", "Memory: 32768K available"},
{"2.100000", "info", "VFS: Mounted root filesystem"},
{"2.750000", "info", "Console: NonameSH terminal"},
{"3.050000", "ok", "System ready. User: root"}
};
cout << "\n";
for (const auto& m : msgs) {
string color = (m.level == "ok") ? clr::success : clr::info;
cout << " " << clr::dgray << "[" << m.ts << "]" << clr::reset << " " << color << m.text << clr::reset << "\n";
}
cout << "\n";
}
void cmd_lscpu() {
cout << "\n";
auto row = [](const string& k, const string& v) {
cout << " " << clr::gray << k << ":" << clr::reset << string(max(0, 20 - (int)k.size()), ' ') << clr::bold << clr::white << v << clr::reset << "\n";
};
row("Architecture", clr::cyan + "x86_64" + clr::reset);
row("CPU op-mode(s)", clr::cyan + "32-bit, 64-bit" + clr::reset);
row("Model name", clr::cyan + "NoNameCPU v1.0" + clr::reset);
row("CPU(s)", clr::cyan + "4" + clr::reset);
row("CPU MHz", clr::cyan + "2400.000" + clr::reset);
row("L1d cache", clr::cyan + "32K" + clr::reset);
row("L1i cache", clr::cyan + "32K" + clr::reset);
row("L2 cache", clr::cyan + "256K" + clr::reset);
row("L3 cache", clr::cyan + "4096K" + clr::reset);
cout << "\n";
}
void cmd_lsusb() {
cout << "\n";
auto row = [](const string& bus, const string& dev, const string& desc) {
cout << " " << clr::white << "Bus " << bus << " Device " << dev << ": " << clr::reset
<< clr::dgray << "ID " << clr::reset << clr::lcyan << desc << clr::reset << "\n";
};
row("001", "001", "1d6b:0001 NoName USB Keyboard");
row("001", "002", "1d6b:0002 NoName USB Mouse");
row("002", "001", "1d6b:0003 NoName Storage Device");
row("002", "002", "1d6b:0004 NoName USB Hub");
cout << "\n";
}
void cmd_arch() { cout << "x86_64\n"; }
void cmd_nproc() { cout << "4\n"; }
// --- VFS ENHANCEMENTS ---
void cmd_du(const string& args, map<string,FSNode>& fs, const string& cdir) {
string a = args;
while (!a.empty() && a.back() == '/') a.pop_back();
string dir = a.empty() ? cdir : (a[0] == '/' ? a + "/" : cdir + a + "/");
size_t total = 0;
for (const auto& [p, n] : fs) {
if (p.rfind(dir, 0) == 0 && !n.is_dir) total += n.size();
}
cout << total << "\t" << (args.empty() ? "." : args) << "\n";
}
void cmd_locate(const string& args, const map<string,FSNode>& fs) {
if (args.empty()) { cout << "Usage: locate <pattern>\n"; return; }
bool found = false;
for (const auto& [p, n] : fs) {
if (p.find(args) != string::npos) { cout << p << "\n"; found = true; }
}
if (!found) cout << "error: no matches found.\n";
}
// --- PRODUCTIVITY ---
void cmd_pom() {
const int FOCUS = 25, BREAK = 5, LONG_BREAK = 15;
for (int cycle = 0; cycle < 4; cycle++) {
cout << "\033[33mFocus round " << (cycle+1) << "/4\033[0m\n";
for (int m = FOCUS; m > 0; m--) {
cout << "\r " << (m < 10 ? " " : "") << m << ":00 remaining [";
int pos = (int)((float)(FOCUS - m) / FOCUS * 20);
for (int i = 0; i < 20; i++) cout << (i < pos ? "\033[32m=\033[0m" : " ");
cout << "]";
cout.flush();
this_thread::sleep_for(chrono::seconds(1));
}
cout << "\n\033[32mFocus complete!\033[0m\n";
if (cycle < 3) {
int blen = cycle == 2 ? LONG_BREAK : BREAK;
cout << "\033[36mBreak for " << blen << " min\033[0m\n";
for (int m = blen; m > 0; m--) {
cout << "\r " << m << ":00 ";
cout.flush();
this_thread::sleep_for(chrono::seconds(1));
}
cout << "\n";
}
}
cout << "\033[32mPomodoro complete! Great work.\033[0m\n";
}
void cmd_alarm(const string& args) {
long long sec = 0;
for (char c : args) {
if (c >= '0' && c <= '9') {
int digit = c - '0';
if (sec > (LLONG_MAX - digit) / 10) { cout << "Usage: alarm <seconds>\n"; return; }
sec = sec * 10 + digit;
}
}
if (sec <= 0 || sec > INT_MAX) { cout << "Usage: alarm <seconds>\n"; return; }
for (int i = (int)sec; i >= 0; i--) {
cout << "\rAlarm in " << i << "s ";
cout.flush();
if (i > 0) this_thread::sleep_for(chrono::seconds(1));
}
cout << "\n\a\033[31m*** ALARM! ***\033[0m\n";
}
void cmd_bc(const string& args, map<string,FSNode>&, const string&) {
if (args.empty()) { cout << "Usage: bc <expression>\n"; return; }
auto precedence = [](char op) -> int {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/' || op == '%') return 2;
if (op == '^') return 3;
return 0;
};
auto apply_op = [](double a, double b, char op) -> double {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': if (b == 0) { cout << "\033[31merror:\033[0m division by zero.\n"; return NAN; } return a / b;
case '%': if (b == 0) { cout << "\033[31merror:\033[0m division by zero.\n"; return NAN; } return fmod(a, b);
case '^': return pow(a, b);
default: return 0;
}
};
vector<double> nums;
vector<char> ops;
istringstream ss(args);
double val; char op;
if (ss >> val) {
nums.push_back(val);
while (ss >> op >> val) {
if (op != '+' && op != '-' && op != '*' && op != '/' && op != '%' && op != '^') {
cout << "error: invalid operator.\n"; return;
}
while (!ops.empty() && (ops.back() == '^' ? precedence(ops.back()) > precedence(op) : precedence(ops.back()) >= precedence(op))) {
if (nums.size() < 2) { cout << "error: invalid expression.\n"; return; }
double b = nums.back(); nums.pop_back();
double a = nums.back(); nums.pop_back();
double r = apply_op(a, b, ops.back());
if (isnan(r)) return;
nums.push_back(r);
ops.pop_back();
}
ops.push_back(op);
nums.push_back(val);
}
}
while (!ops.empty()) {
if (nums.size() < 2) { cout << "error: invalid expression.\n"; return; }
double b = nums.back(); nums.pop_back();
double a = nums.back(); nums.pop_back();
double r = apply_op(a, b, ops.back());
if (isnan(r)) return;
nums.push_back(r);
ops.pop_back();
}
if (!nums.empty()) cout << "= " << nums.back() << "\n";
}
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 8: Built-in Games (24+ games)
// ══════════════════════════════════════════════════════════════════════════════
// Each game runs in its own loop with ANSI rendering
// Games use kbhit()/getkey() for non-blocking input
// Arrow keys and WASD supported in all real-time games
// --- ASCIIDASH ENGINE ---
// A side-scrolling obstacle runner that renders frames using ANSI escape sequences
// Controls: SPACE or ENTER to jump over '^' obstacles
void play_asciidash(string map_data) {
cout << "\033[2J\033[1;1H";
cout << "INITIALIZING ASCIIDASH ENGINE...\n";
boot_delay(1000);
int player_y = 0;
int jump_timer = 0;
bool crashed = false;
string pad(ASCIIDASH_PADDING, '_');
map_data = pad + map_data + pad;
size_t map_len = map_data.length();
if (map_len <= static_cast<size_t>(ASCIIDASH_PADDING) / 2 + 1) { cout << "Map too short.\n"; return; }
for (size_t i = 0; i < map_len - static_cast<size_t>(ASCIIDASH_PADDING) / 2; i++) {
if (kbhit()) {
int k = getkey();
if ((k == KEY_SPACE || k == KEY_UP || k == 'w') && player_y == 0) {
player_y = 1;
jump_timer = JUMP_FRAMES;
}
}
if (jump_timer > 0) {
jump_timer--;
} else {
player_y = 0;
}
if (player_y == 0 && map_data[i + ASCIIDASH_PADDING / 2] == '^') {
crashed = true;
break;
}
cout << "\033[2J\033[1;1H";
cout << "\n " << clr::bold << clr::cyan << "🚀 ASCIIDASH" << clr::reset << " " << clr::dgray << VERSION << clr::reset << " " << clr::gray << "(SPACE/W/↑=jump)" << clr::reset << "\n\n";
cout << (player_y == 1 ? " ■\n" : "\n");
cout << " " << (player_y == 0 ? "■" : " ") << "\n";
cout << map_data.substr(i, ASCIIDASH_WINDOW) << "\n";
cout << "====================\n";
this_thread::sleep_for(chrono::milliseconds(GAME_SPEED_MS));
}
while (kbhit()) (void)getchar();
cout << "\n\n";
if (crashed) {
cout << "\n " << clr::error << ">> CRASHED! Attempt failed." << clr::reset << "\n";
} else {
cout << "\n " << clr::success << ">> LEVEL COMPLETE! GG!" << clr::reset << "\n";
}
cout << "Press Enter to return to NoNameOS...";
cooked_readline();
}
void play_snake() {
vector<pair<int,int>> snake = {{SNAKE_W/2, SNAKE_H/2}};
int dx = 1, dy = 0;
int food_x = rng_int(0, SNAKE_W - 1), food_y = rng_int(0, SNAKE_H - 1);
int score = 0;
bool game_over = false;
while (!game_over) {
if (kbhit()) {
int k = getkey();
if ((k == 'w' || k == KEY_UP) && dy == 0) { dx = 0; dy = -1; }
else if ((k == 's' || k == KEY_DOWN) && dy == 0) { dx = 0; dy = 1; }
else if ((k == 'a' || k == KEY_LEFT) && dx == 0) { dx = -1; dy = 0; }
else if ((k == 'd' || k == KEY_RIGHT) && dx == 0) { dx = 1; dy = 0; }
}
int nx = snake[0].first + dx;
int ny = snake[0].second + dy;
if (nx < 0 || nx >= SNAKE_W || ny < 0 || ny >= SNAKE_H) {
break;
}
bool eating = (nx == food_x && ny == food_y);
size_t check_len = eating ? snake.size() : snake.size() - 1;
for (size_t i = 0; i < check_len; i++) {
if (snake[i].first == nx && snake[i].second == ny) {
game_over = true;
break;
}
}
if (game_over) break;
snake.insert(snake.begin(), {nx, ny});
if (eating) {
score++;
// Spawn food not on snake body
vector<pair<int,int>> empty_cells;
for (int fy = 0; fy < SNAKE_H; fy++)
for (int fx = 0; fx < SNAKE_W; fx++) {
bool on_snake = false;
for (const auto& seg : snake) if (seg.first == fx && seg.second == fy) { on_snake = true; break; }
if (!on_snake) empty_cells.push_back({fx, fy});
}
if (!empty_cells.empty()) {
auto [fx, fy] = empty_cells[rng_int(0, (int)empty_cells.size() - 1)];
food_x = fx; food_y = fy;
}
} else {
snake.pop_back();
}
vector<vector<bool>> grid(SNAKE_H, vector<bool>(SNAKE_W, false));
for (size_t i = 0; i < snake.size(); i++) {
grid[snake[i].second][snake[i].first] = true;
}
cout << "\033[2J\033[1;1H";
cout << "\n " << clr::bold << clr::green << "🐍 SNAKE" << clr::reset << " " << clr::dgray << "v1.0" << clr::reset << " " << clr::gray << "Score:" << clr::reset << " " << clr::yellow << score << clr::reset << " " << clr::dgray << "(WASD/Arrows to move)" << clr::reset << "\n\n";
for (int y = 0; y < SNAKE_H; y++) {
cout << " ";
for (int x = 0; x < SNAKE_W; x++) {
if (grid[y][x]) {
if (snake[0].first == x && snake[0].second == y)
cout << clr::bold << clr::green << "O" << clr::reset;
else
cout << clr::cyan << "o" << clr::reset;
} else if (x == food_x && y == food_y) {
cout << clr::bold << clr::red << "*" << clr::reset;
} else {
cout << ".";
}
}
cout << "\n";
}
cout << "\n " << clr::gray << "Score: " << clr::yellow << score << clr::gray << " │ Press Ctrl+C to quit" << clr::reset << "\n";
this_thread::sleep_for(chrono::milliseconds(GAME_SPEED_MS));
}
while (kbhit()) (void)getchar();
string sc = to_string(score);
cout << "\n\n " << clr::error << ">> GAME OVER" << clr::reset << " " << clr::gray << "Final Score:" << clr::reset << " " << clr::yellow << sc << clr::reset << "\n";
cout << "Press Enter to return to NoNameOS...";
cooked_readline();
}
void play_minesweeper() {
vector<vector<char>> board(MINESWEEPER_H, vector<char>(MINESWEEPER_W, '.'));
vector<vector<bool>> revealed(MINESWEEPER_H, vector<bool>(MINESWEEPER_W, false));
vector<vector<bool>> mines(MINESWEEPER_H, vector<bool>(MINESWEEPER_W, false));
int remaining = MINESWEEPER_W * MINESWEEPER_H - MINESWEEPER_MINES;
bool game_over = false;
bool won = false;