-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1423 lines (1308 loc) · 49.9 KB
/
main.cpp
File metadata and controls
1423 lines (1308 loc) · 49.9 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
#include <filesystem>
#include <iostream>
#include <deque>
#include <utility>
#include <sstream>
#include <algorithm>
#include "utils.h"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#endif
#include "OES.h"
#include "iNode.h"
#include "filesystem.h"
#include "OpenES/layer/interface.h"
namespace fs = std::filesystem;
// ==================== Color Support ====================
class ColorSupport {
bool enabled_ = true;
public:
ColorSupport() {
#ifdef _WIN32
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode;
enabled_ = GetConsoleMode(h, &mode) &&
SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#else
const char *term = getenv("TERM");
const char *colorterm = getenv("COLORTERM");
enabled_ = isatty(STDOUT_FILENO) &&
(colorterm || (term && strstr(term, "color")));
#endif
}
[[nodiscard]] std::string red(const std::string &s) const { return enabled_ ? "\033[91m" + s + "\033[0m" : s; }
[[nodiscard]] std::string green(const std::string &s) const { return enabled_ ? "\033[92m" + s + "\033[0m" : s; }
[[nodiscard]] std::string yellow(const std::string &s) const { return enabled_ ? "\033[93m" + s + "\033[0m" : s; }
[[nodiscard]] std::string blue(const std::string &s) const { return enabled_ ? "\033[94m" + s + "\033[0m" : s; }
[[nodiscard]] std::string cyan(const std::string &s) const { return enabled_ ? "\033[96m" + s + "\033[0m" : s; }
[[nodiscard]] std::string bold(const std::string &s) const { return enabled_ ? "\033[1m" + s + "\033[0m" : s; }
[[nodiscard]] std::string boldGreen(const std::string &s) const {
return enabled_ ? "\033[1;32m" + s + "\033[0m" : s;
}
[[nodiscard]] std::string boldBlue(const std::string &s) const {
return enabled_ ? "\033[1;34m" + s + "\033[0m" : s;
}
[[nodiscard]] std::string dim(const std::string &s) const { return enabled_ ? "\033[2m" + s + "\033[0m" : s; }
[[nodiscard]] std::string progressBar(float p) const {
if (!enabled_) {
const int pos = static_cast<int>(40 * p);
std::string bar(pos, '#');
bar += std::string(40 - pos, ' ');
return "[" + bar + "]";
}
const std::string col = p < 0.3 ? "\033[91m" : p < 0.7 ? "\033[93m" : "\033[92m";
const int pos = static_cast<int>(40 * p);
std::string bar;
for (int i = 0; i < 40; i++) bar += (i < pos ? "█" : i == pos ? "▶" : " ");
return "[" + col + bar + "\033[0m]";
}
[[nodiscard]] bool isEnabled() const { return enabled_; }
};
static ColorSupport g_colors;
// ==================== Pre-calculation Structures ====================
struct FileEntry {
std::string fsPath;
std::string internalPath;
size_t size;
bool isDirectory;
};
struct PreCalculatedBatch {
std::vector<FileEntry> entries;
size_t totalSize = 0;
size_t fileCount = 0;
size_t dirCount = 0;
void clear() {
entries.clear();
totalSize = fileCount = dirCount = 0;
}
[[nodiscard]] size_t getAllocationSize() const {
return static_cast<size_t>(totalSize * 1.2) + (fileCount + dirCount) * 512;
}
};
void scanAndCalculate(const std::string &fsPath, const std::string &basePath, PreCalculatedBatch &batch) {
for (const auto &e: Filesystem::listDirectory(fsPath)) {
std::string fullFsPath = Filesystem::joinPath(fsPath, e.name);
std::string internalPath = basePath.empty() ? e.name : basePath + "/" + e.name;
FileEntry fe{fullFsPath, internalPath, e.isDirectory ? 0 : Filesystem::getFileSize(fullFsPath), e.isDirectory};
batch.entries.push_back(fe);
if (e.isDirectory) {
batch.dirCount++;
scanAndCalculate(fullFsPath, internalPath, batch);
} else {
batch.fileCount++;
batch.totalSize += fe.size;
}
}
}
PreCalculatedBatch calculateSingleFile(const std::string &fsPath, const std::string &internalPath) {
PreCalculatedBatch batch;
size_t sz = Filesystem::getFileSize(fsPath);
batch.entries.push_back({fsPath, internalPath, sz, false});
batch.fileCount = 1;
batch.totalSize = sz;
return batch;
}
PreCalculatedBatch calculateDirectory(const std::string &fsPath) {
PreCalculatedBatch batch;
scanAndCalculate(fsPath, "", batch);
return batch;
}
// ==================== Utility Functions ====================
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
std::string getPassword(const std::string &prompt = "Password: ") {
std::cout << prompt;
std::string password;
#ifdef _WIN32
char ch;
while ((ch = _getch()) != '\r') {
if (ch == '\b' && !password.empty()) {
password.pop_back();
std::cout << "\b \b";
} else if (ch != '\b') {
password += ch;
std::cout << '*';
}
}
#else
termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
std::getline(std::cin, password);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#endif
std::cout << std::endl;
return password;
}
std::string getInput(const std::string &prompt) {
std::cout << prompt;
std::string input;
std::getline(std::cin, input);
return input;
}
void pressEnterToContinue() {
std::cout << "\nPress ENTER to continue...";
std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
}
std::string formatSize(size_t bytes) {
const char *units[] = {"B", "KB", "MB", "GB"};
int unit = 0;
auto size = static_cast<double>(bytes);
while (size >= 1024 && unit < 3) {
size /= 1024;
unit++;
}
std::ostringstream oss;
oss << std::fixed << std::setprecision(unit ? 2 : 0) << size << " " << units[unit];
return oss.str();
}
void printSuccess(const std::string &msg) { std::cout << g_colors.green("[OK] ") << msg << "\n"; }
void printError(const std::string &msg, const std::string &hint = "") {
std::cout << g_colors.red("[ERROR] ") << msg << "\n";
if (!hint.empty()) std::cout << g_colors.dim(" Hint: " + hint) << "\n";
}
void printWarning(const std::string &msg) { std::cout << g_colors.yellow("[WARN] ") << msg << "\n"; }
void printInfo(const std::string &msg) { std::cout << g_colors.cyan("[INFO] ") << msg << "\n"; }
class ProgressTracker {
std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now();
int total_;
std::string op_;
bool showProgress_;
public:
ProgressTracker(int t, std::string o, bool show = true)
: total_(t), op_(std::move(o)), showProgress_(show && t > 5) {
}
void update(int cur) const {
if (!showProgress_) return;
float p = total_ > 0 ? float(cur) / total_ : 0;
std::cout << "\r" << op_ << ": " << g_colors.progressBar(p) << " "
<< std::fixed << std::setprecision(1) << p * 100 << "% (" << cur << "/" << total_ << ")";
if (cur > 0 && cur < total_) {
auto el = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - start_).count();
if (el > 0) {
int rem = static_cast<int>((total_ - cur) * el / cur);
std::cout << " ETA:" << rem / 60 << ":" << std::setw(2) << std::setfill('0')
<< rem % 60 << std::setfill(' ');
}
}
std::cout << " ";
std::cout.flush();
}
void finish() const {
if (showProgress_)
std::cout << "\r" << op_ << ": " << g_colors.progressBar(1.0) <<
" 100% Done! \n";
else printSuccess(op_ + " completed");
}
};
std::vector<std::string> splitCommand(const std::string &cmd) {
std::vector<std::string> tokens;
std::string cur;
bool dq = false, sq = false, esc = false;
for (char c: cmd) {
if (esc) {
cur += c;
esc = false;
continue;
}
if (c == '\\') {
esc = true;
continue;
}
if (c == '"' && !sq) {
dq = !dq;
continue;
}
if (c == '\'' && !dq) {
sq = !sq;
continue;
}
if (c == ' ' && !dq && !sq) {
if (!cur.empty()) {
tokens.push_back(cur);
cur.clear();
}
} else cur += c;
}
if (!cur.empty()) tokens.push_back(cur);
return tokens;
}
void printHeader(const std::string &title) {
clearScreen();
std::string line(42, '=');
std::cout << "+" << line << "+\n|" << std::string((42 - title.length()) / 2, ' ')
<< g_colors.bold(title) << std::string((43 - title.length()) / 2, ' ')
<< "|\n+" << line << "+\n\n";
}
std::string normalizePath(const std::string &base, const std::string &path) {
if (path.empty() || path == ".") return base;
std::vector<std::string> parts;
if (path[0] != '/' && base != "/" && !base.empty()) {
std::istringstream iss(base);
std::string seg;
while (std::getline(iss, seg, '/')) if (!seg.empty()) parts.push_back(seg);
}
std::istringstream iss(path);
std::string seg;
while (std::getline(iss, seg, '/')) {
if (seg.empty() || seg == ".") continue;
if (seg == "..") { if (!parts.empty()) parts.pop_back(); } else parts.push_back(seg);
}
if (parts.empty()) return "/";
std::string result;
for (const auto &p: parts) result += "/" + p;
return result;
}
std::string toInternalPath(const std::string &dp) {
return (dp.empty() || dp == "/") ? "" : (dp[0] == '/' ? dp.substr(1) : dp);
}
// ==================== Command History ====================
class CommandHistory {
std::deque<std::string> history_;
size_t maxSize_ = 100;
int position_ = -1;
public:
void add(const std::string &cmd) {
if (cmd.empty() || (!history_.empty() && history_.back() == cmd)) return;
history_.push_back(cmd);
if (history_.size() > maxSize_) history_.pop_front();
position_ = -1;
}
std::string navigateUp(const std::string ¤t) {
if (history_.empty()) return current;
if (position_ == -1) position_ = history_.size();
if (position_ > 0) position_--;
return history_[position_];
}
std::string navigateDown(const std::string ¤t) {
if (history_.empty() || position_ == -1) return current;
if (position_ < (int) history_.size() - 1) {
position_++;
return history_[position_];
}
position_ = -1;
return "";
}
void resetPosition() { position_ = -1; }
};
// ==================== Line Editor ====================
class LineEditor {
iNode *node_;
std::string cwd_, line_;
size_t cursor_ = 0;
bool useFs_ = false;
CommandHistory history_;
[[nodiscard]] std::string getLastToken() const {
const auto p = line_.rfind(' ');
return p == std::string::npos ? line_ : line_.substr(p + 1);
}
[[nodiscard]] size_t getLastTokenStart() const {
auto p = line_.rfind(' ');
return p == std::string::npos ? 0 : p + 1;
}
static std::vector<std::string> getFsCompletions(const std::string &partial) {
std::vector<std::string> c;
std::string dir, pre;
const auto ls = partial.rfind('/');
const auto bs = partial.rfind('\\');
const auto sep = (ls != std::string::npos && bs != std::string::npos)
? (std::max)(ls, bs)
: (ls != std::string::npos ? ls : bs);
if (sep == std::string::npos) {
dir = ".";
pre = partial;
} else {
dir = partial.substr(0, sep + 1);
pre = partial.substr(sep + 1);
}
try {
for (const auto &e: Filesystem::listDirectory(dir.empty() ? "." : dir))
if (pre.empty() || e.name.find(pre) == 0)
c.push_back(dir + e.name + (e.isDirectory ? "/" : ""));
} catch (...) {
}
std::sort(c.begin(), c.end());
return c;
}
[[nodiscard]] std::vector<std::string> getLbCompletions(const std::string &partial) const {
std::vector<std::string> c;
if (!node_) return c;
std::string dir, pre;
const auto ls = partial.rfind('/');
if (ls == std::string::npos) {
dir = toInternalPath(cwd_);
pre = partial;
} else {
pre = partial.substr(ls + 1);
dir = partial[0] == '/'
? toInternalPath(partial.substr(0, ls))
: toInternalPath(normalizePath(cwd_, partial.substr(0, ls)));
}
for (const auto &e: node_->listDirectory(dir))
if (pre.empty() || e.plainName.find(pre) == 0)
c.push_back(
(ls != std::string::npos ? partial.substr(0, ls + 1) : "") + e.plainName + (e.isFile ? "" : "/"));
std::sort(c.begin(), c.end());
return c;
}
void redraw(const std::string &pr) const {
std::cout << "\r\033[K" << pr << line_;
if (cursor_ < line_.length()) std::cout << "\033[" << (line_.length() - cursor_) << "D";
std::cout.flush();
}
void handleTab(const std::string &pr) {
auto partial = getLastToken();
auto comps = useFs_ ? getFsCompletions(partial) : getLbCompletions(partial);
if (comps.empty()) return;
auto ts = getLastTokenStart();
if (comps.size() == 1) {
auto cm = comps[0];
if (cm.find(' ') != std::string::npos) cm = "\"" + cm + "\"";
line_ = line_.substr(0, ts) + cm;
cursor_ = line_.length();
redraw(pr);
} else {
std::cout << "\n";
for (const auto &x: comps) std::cout << " " << x << "\n";
std::string com = comps[0];
for (size_t i = 1; i < comps.size(); i++) {
size_t j = 0;
while (j < com.length() && j < comps[i].length() && com[j] == comps[i][j]) j++;
com = com.substr(0, j);
}
line_ = line_.substr(0, ts) + com;
cursor_ = line_.length();
std::cout << pr << line_;
std::cout.flush();
}
}
void handleHistory(bool up, const std::string &pr) {
line_ = up ? history_.navigateUp(line_) : history_.navigateDown(line_);
cursor_ = line_.length();
redraw(pr);
}
public:
explicit LineEditor(iNode *n = nullptr, std::string c = "/") : node_(n), cwd_(std::move(c)), useFs_(n == nullptr) {
}
void setNode(iNode *n) {
node_ = n;
useFs_ = !n;
}
void setCwd(const std::string &c) { cwd_ = c; }
void setFilesystemMode(bool f) { useFs_ = f; }
std::string readLine(const std::string &pr) {
line_.clear();
cursor_ = 0;
history_.resetPosition();
std::cout << pr;
std::cout.flush();
#ifdef _WIN32
while (true) {
if (int ch = _getch(); ch == '\r' || ch == '\n') {
std::cout << "\n";
history_.add(line_);
return line_;
} else if (ch == '\t') handleTab(pr);
else if (ch == '\b' || ch == 127) {
if (cursor_ > 0) {
line_.erase(--cursor_, 1);
redraw(pr);
}
} else if (ch == 0 || ch == 224) {
ch = _getch();
if (ch == 75 && cursor_ > 0) {
cursor_--;
std::cout << "\033[D";
} else if (ch == 77 && cursor_ < line_.length()) {
cursor_++;
std::cout << "\033[C";
} else if (ch == 72) handleHistory(true, pr);
else if (ch == 80) handleHistory(false, pr);
} else if (ch >= 32) {
line_.insert(cursor_++, 1, char(ch));
redraw(pr);
}
}
#else
termios o, n;
tcgetattr(STDIN_FILENO, &o);
n = o;
n.c_lflag &= ~(ICANON | ECHO);
n.c_cc[VMIN] = 1;
n.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &n);
while (true) {
char ch;
read(STDIN_FILENO, &ch, 1);
if (ch == '\n' || ch == '\r') {
std::cout << "\n";
tcsetattr(STDIN_FILENO, TCSANOW, &o);
history_.add(line_);
return line_;
} else if (ch == '\t') handleTab(pr);
else if (ch == 127 || ch == '\b') {
if (cursor_ > 0) {
line_.erase(--cursor_, 1);
redraw(pr);
}
} else if (ch == 27) {
char s[2];
read(STDIN_FILENO, s, 2);
if (s[0] == '[') {
if (s[1] == 'D' && cursor_ > 0) {
cursor_--;
std::cout << "\033[D";
} else if (s[1] == 'C' && cursor_ < line_.length()) {
cursor_++;
std::cout << "\033[C";
} else if (s[1] == 'A') handleHistory(true, pr);
else if (s[1] == 'B') handleHistory(false, pr);
std::cout.flush();
}
} else if (ch >= 32) {
line_.insert(cursor_++, 1, ch);
redraw(pr);
}
}
tcsetattr(STDIN_FILENO, TCSANOW, &o);
#endif
}
};
LineEditor g_fsEditor(nullptr);
std::string getPathWithCompletion(const std::string &pr) {
g_fsEditor.setFilesystemMode(true);
auto p = g_fsEditor.readLine(pr);
if (!p.empty() && p.front() == '"') p.erase(0, 1);
if (!p.empty() && p.back() == '"') p.pop_back();
return p;
}
// ==================== Batch Insert ====================
bool insertBatchIntoLockbox(iNode *node, const PreCalculatedBatch &batch, bool showProg = true) {
if (batch.entries.empty()) return true;
if (showProg && batch.fileCount > 5) {
printInfo("Processing " + formatSize(batch.getAllocationSize()) + " of data...");
}
int proc = 0;
int errors = 0;
const int tot = static_cast<int>(batch.entries.size());
const ProgressTracker prog(tot, "Encrypting", showProg);
node->beginBulkUpdate();
try {
for (const auto &[fsPath, internalPath, size, isDirectory]: batch.entries) {
if (isDirectory) {
if (node->addDirectory(internalPath) == 0) {
printWarning("Failed to create directory: " + internalPath);
errors++;
}
} else {
// Gestisce TUTTI i file, inclusi quelli vuoti (size == 0)
try {
if (size == 0) {
// File vuoto: aggiungi con buffer vuoto o nullptr
node->addFile(internalPath, nullptr, 0);
} else {
// File con contenuto
auto [sz, buf] = Filesystem::readFile(fsPath);
if (buf.empty() && sz == 0 && size > 0) {
printWarning("Failed to read: " + fsPath + " (" + formatSize(size) + ")");
errors++;
continue;
}
node->addFile(internalPath, buf.data(), sz);
}
} catch (const std::exception &ex) {
printError("Failed: " + internalPath, ex.what());
errors++;
}
}
prog.update(++proc);
}
} catch (...) {
node->endBulkUpdate();
throw;
}
node->endBulkUpdate();
prog.finish();
if (errors > 0) {
printWarning("Completed with " + std::to_string(errors) + " error(s)");
}
return errors == 0;
}
// ==================== Help System ====================
struct CommandHelp {
std::string name;
std::string args;
std::string description;
};
const std::vector<CommandHelp> CLI_COMMANDS = {
{"ls", "[path]", "List directory contents"},
{"cd", "<path>", "Change current directory"},
{"pwd", "", "Print working directory"},
{"cat", "<file>", "Display file contents"},
{"rm", "<path>", "Remove file or directory (with confirmation)"},
{"mkdir", "<path>", "Create a new directory"},
{"mv", "<src> <dst>", "Move or rename a file/directory"},
{"cp", "<src> <dst>", "Copy a file or directory"},
{"rename", "<path> <name>", "Rename a file or directory"},
{"find", "<pattern>", "Search for files matching pattern"},
{"tree", "[path]", "Display directory tree structure"},
{"extract", "[src] <dst>", "Export files to filesystem"},
{"add", "<file> [path]", "Add file or directory from filesystem"},
{"info", "<path>", "Show detailed information about a path"},
{"limit", "[n]", "Set/show max items displayed in ls"},
{"clear", "", "Clear the terminal screen"},
{"help", "[cmd]", "Show this help or help for specific command"},
{"exit", "", "Exit CLI mode and return to menu"},
};
void printHelp(const std::string &cmd = "") {
if (cmd.empty()) {
std::cout << g_colors.bold("\nAvailable Commands:\n\n");
for (const auto &c: CLI_COMMANDS) {
std::cout << " " << g_colors.green(c.name);
if (!c.args.empty()) std::cout << " " << g_colors.dim(c.args);
std::cout << "\n " << c.description << "\n";
}
std::cout << "\n" << g_colors.dim("Use TAB for auto-completion, UP/DOWN for command history\n");
} else {
for (const auto &c: CLI_COMMANDS) {
if (c.name == cmd) {
std::cout << "\n" << g_colors.bold(c.name);
if (!c.args.empty()) std::cout << " " << c.args;
std::cout << "\n " << c.description << "\n";
return;
}
}
printError("Unknown command: " + cmd, "Type 'help' to see available commands");
}
}
// ==================== Menu Functions ====================
void showMainMenu();
void openLockbox();
void createLockbox();
void encryptText();
void decryptText();
void managementMenu(iNode *node);
void cliMode(iNode *node);
void printUsage(const char *prog);
int handleArgs(int argc, char *argv[]);
void showMainMenu() {
while (true) {
printHeader("LOCKBOX - Main Menu");
std::cout << " [1] Open LockBox\n [2] Create LockBox\n [3] Encrypt text\n"
<< " [4] Decrypt text\n [0] Exit\n\n>> ";
std::string ch;
std::getline(std::cin, ch);
if (ch == "1") openLockbox();
else if (ch == "2") createLockbox();
else if (ch == "3") encryptText();
else if (ch == "4") decryptText();
else if (ch == "0") {
std::cout << "Goodbye!\n";
return;
} else {
printError("Invalid choice", "Enter a number between 0-4");
pressEnterToContinue();
}
}
}
void openLockbox() {
printHeader("Open LockBox");
auto path = getPathWithCompletion("LockBox path: ");
if (path.empty()) {
printError("No path specified", "Enter the path to your LockBox file");
pressEnterToContinue();
return;
}
if (!Filesystem::exists(path)) {
printError("File not found: " + path, "Check the path and try again");
pressEnterToContinue();
return;
}
if (Filesystem::isDirectory(path)) {
printError("Path is a directory", "Specify a LockBox file, not a directory");
pressEnterToContinue();
return;
}
auto pwd = getPassword();
if (pwd.empty()) {
printError("Empty password", "Password is required to open a LockBox");
pressEnterToContinue();
return;
}
auto *oes = new OES();
oes->set_key(const_cast<char *>(pwd.c_str()));
oes->extendWKey(OES_NUM_OF_BLOCKS);
try {
auto *node = new iNode(path, oes);
printSuccess("LockBox opened successfully!");
pressEnterToContinue();
managementMenu(node);
delete node;
} catch (const std::exception &e) {
printError("Failed to open LockBox", "Wrong password or corrupted file");
pressEnterToContinue();
}
delete oes;
}
void createLockbox() {
printHeader("Create LockBox");
const auto src = getPathWithCompletion("Source path: ");
if (src.empty() || !Filesystem::exists(src)) {
printError("Invalid source path", "Specify an existing file or directory");
pressEnterToContinue();
return;
}
auto dst = getPathWithCompletion("Destination path: ");
if (dst.empty()) {
printError("Invalid destination", "Specify where to save the LockBox");
pressEnterToContinue();
return;
}
if (Filesystem::exists(dst)) {
std::cout << "File exists. Overwrite? (y/n): ";
std::string c;
std::getline(std::cin, c);
if (c != "y" && c != "Y") {
printInfo("Operation cancelled");
pressEnterToContinue();
return;
}
}
auto pwd = getPassword();
if (pwd.empty()) {
printError("Empty password");
pressEnterToContinue();
return;
}
if (pwd.length() < 8) {
printWarning("Password is short (< 8 chars).");
}
auto pwd2 = getPassword("Confirm password: ");
if (pwd != pwd2) {
printError("Passwords do not match");
pressEnterToContinue();
return;
}
printInfo("Scanning files...");
const PreCalculatedBatch batch = Filesystem::isDirectory(src)
? calculateDirectory(src)
: calculateSingleFile(src, Filesystem::getFilename(src));
std::cout << " Directories: " << batch.dirCount << " | Files: " << batch.fileCount
<< " | Size: " << formatSize(batch.totalSize) << "\n\n";
auto *oes = new OES();
oes->set_key(const_cast<char *>(pwd.c_str()));
oes->extendWKey(OES_NUM_OF_BLOCKS);
try {
auto *node = new iNode(dst, oes);
insertBatchIntoLockbox(node, batch, true);
printInfo("Saving LockBox...");
node->save();
printSuccess("LockBox created successfully!");
pressEnterToContinue();
managementMenu(node);
delete node;
} catch (const std::exception &e) {
printError("Failed to create LockBox", e.what());
pressEnterToContinue();
}
delete oes;
}
void encryptText() {
printHeader("Encrypt Text");
auto txt = getInput("Text to encrypt: ");
if (txt.empty()) {
printError("No text provided");
pressEnterToContinue();
return;
}
const auto pwd = getPassword();
if (pwd.empty()) {
printError("Empty password");
pressEnterToContinue();
return;
}
auto iv = getInput("IV (optional, press Enter to skip): ");
auto *oes = new OES();
oes->set_key(const_cast<char *>(pwd.c_str()));
oes->extendWKey(OES_NUM_OF_BLOCKS);
if (!iv.empty()) {
auto *b = MBLOCK::fromBytes(iv.c_str(), iv.length());
if (b) {
oes->setIV(b->getDataRef(), b->getLen());
delete b;
}
}
try {
oes->load_data_raw(const_cast<char *>(txt.c_str()), txt.length());
oes->enc_adv();
if (auto *cb = oes->get_cipherBlock(); cb && !cb->isNull()) {
auto [d, s] = exportBlock(cb, OES_TYPE_HEX);
if (auto h = static_cast<char *>(d)) {
printSuccess("Encrypted:");
std::cout << "\n" << h << "\n";
free(h);
}
}
} catch (const std::exception &e) { printError("Encryption failed", e.what()); }
delete oes;
pressEnterToContinue();
}
void decryptText() {
printHeader("Decrypt Text");
auto hex = getInput("Hex ciphertext: ");
if (hex.empty()) {
printError("No ciphertext provided");
pressEnterToContinue();
return;
}
auto pwd = getPassword();
if (pwd.empty()) {
printError("Empty password");
pressEnterToContinue();
return;
}
auto iv = getInput("IV (optional, press Enter to skip): ");
auto *ib = importBlock(hex.c_str(), hex.length(), OES_TYPE_HEX);
if (!ib) {
printError("Invalid hex format", "Ensure the ciphertext is valid hexadecimal");
pressEnterToContinue();
return;
}
auto *oes = new OES();
oes->set_key(const_cast<char *>(pwd.c_str()));
oes->extendWKey(OES_NUM_OF_BLOCKS);
if (!iv.empty()) {
auto *b = MBLOCK::fromBytes(iv.c_str(), iv.length());
if (b) {
oes->setIV(b->getDataRef(), b->getLen());
delete b;
}
}
oes->load_cipher_block(ib, true);
oes->dec_adv();
if (auto *pb = oes->get_plainBlock(); pb && !pb->isNull()) {
auto r = pb->toBytes();
printSuccess("Decrypted:");
std::cout << "\n";
std::cout.write(reinterpret_cast<char *>(r.first), r.second);
std::cout << "\n";
delete[] r.first;
} else { printError("Decryption failed", "Wrong password or corrupted data"); }
delete oes;
pressEnterToContinue();
}
void managementMenu(iNode *node) {
while (true) {
printHeader("LockBox Management");
node->printStats();
std::cout << "\n [1] Extract [2] CLI Mode [3] Search [4] Defragment\n"
<< " [5] View Log [6] Clear Log [0] Save & Exit\n\n>> ";
std::string cmd;
std::getline(std::cin, cmd);
auto tk = splitCommand(cmd);
if (tk.empty()) continue;
if (tk[0] == "0") {
node->save();
printSuccess("LockBox saved successfully!");
pressEnterToContinue();
return;
}
if (tk[0] == "1") {
auto pp = tk.size() > 1 ? tk[1] : "";
auto dest = getPathWithCompletion("Destination folder: ");
if (dest.empty()) {
printError("No destination specified");
pressEnterToContinue();
continue;
}
if (!Filesystem::exists(dest)) Filesystem::createDirectory(dest, true);
try {
node->exportTo(dest, pp);
printSuccess("Extracted to " + dest);
} catch (const std::exception &e) { printError("Extraction failed", e.what()); }
pressEnterToContinue();
} else if (tk[0] == "2") cliMode(node);
else if (tk[0] == "3") {
if (tk.size() < 2) { printError("No search term", "Usage: 3 <filename>"); } else {
auto r = node->search(tk[1], false);
if (r.empty()) printInfo("No results found for: " + tk[1]);
else {
printSuccess("Found " + std::to_string(r.size()) + " result(s):");
for (const auto &p: r)
std::cout << " " << (node->exists(p, true) ? "📄 " : "📁 ") << p << "\n";
}
}
pressEnterToContinue();
} else if (tk[0] == "4") {
printInfo("Running defragmentation...");
if (node->defragment()) printSuccess("Defragmentation completed");
else printError("Defragmentation failed");
pressEnterToContinue();
} else if (tk[0] == "5") {
std::cout << "\n" << g_colors.bold("=== Activity Log ===") << "\n"
<< node->getLog() << g_colors.bold("====================") << "\n"
<< "Log size: " << formatSize(node->getLogSize()) << "\n";
pressEnterToContinue();
} else if (tk[0] == "6") {
std::cout << "Clear activity log? (y/n): ";
std::string c;
std::getline(std::cin, c);
if (c == "y" || c == "Y") {
node->clearLog();
printSuccess("Log cleared");
}
pressEnterToContinue();
} else {
printError("Invalid option");
pressEnterToContinue();
}
}
}
void cliMode(iNode *node) {
std::string cwd = "/";
int maxIt = 10;
LineEditor ed(node, cwd);
auto toInt = [&](const std::string &p) { return toInternalPath(normalizePath(cwd, p)); };
auto toDisp = [&](const std::string &p) { return normalizePath(cwd, p); };
auto listDir = [&](const std::string &pp) {
auto ent = node->listDirectory(pp);
if (ent.empty()) {
std::cout << " (empty directory)\n";
return;
}
// Sort: directories first (isFile=false), then by name
std::sort(ent.begin(), ent.end(), [](const iNode::DirEntry &a, const iNode::DirEntry &b) {
return a.isFile != b.isFile ? a.isFile < b.isFile : a.plainName < b.plainName;
});
int sh = 0;
for (const auto &e: ent) {
if (sh >= maxIt) {
std::cout << g_colors.dim(" ... " + std::to_string(ent.size() - maxIt) + " more items\n");
break;
}
std::cout << (e.isFile ? " 📄 " : " 📁 ") << e.plainName
<< (e.isFile ? " (" + formatSize(e.size) + ")" : "/") << "\n";
sh++;
}
std::cout << g_colors.dim("Total: " + std::to_string(ent.size()) + " items\n");