-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniNotes.ino
More file actions
1043 lines (913 loc) · 34.7 KB
/
MiniNotes.ino
File metadata and controls
1043 lines (913 loc) · 34.7 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 <WiFi.h>
#include <WebServer.h>
#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <vector>
#include <algorithm>
#define PIN_SD_CS 5
#define PIN_OLED_SDA 14
#define PIN_OLED_SCL 22
#define PIN_BTN_UP 32
#define PIN_BTN_DOWN 33
#define PIN_SD_CS 5
#define PIN_SD_MOSI 23
#define PIN_SD_MISO 1 // 👈 CHANGED TO GPIO2
#define PIN_SD_SCK 18
#define PIN_OLED_SDA 14
#define PIN_OLED_SCL 22
#define PIN_BTN_UP 32
#define PIN_BTN_DOWN 33
#define OLED_W 128
#define OLED_H 64
#define OLED_ADDR 0x3C
Adafruit_SSD1306 oled(OLED_W, OLED_H, &Wire, -1);
const char* AP_SSID = "CheatCode";
const char* AP_PASS = "letscheat";
WebServer server(80);
bool wifiEnabled = true; // ← NEW: tracks AP state
#define BTN_DEBOUNCE_MS 50
#define BTN_LONGPRESS_MS 700
struct Btn {
uint8_t pin;
bool prevState;
bool shortPress;
bool longPress;
unsigned long pressedAt;
bool longFired;
};
Btn btnUp = { PIN_BTN_UP, HIGH, false, false, 0, false };
Btn btnDown = { PIN_BTN_DOWN, HIGH, false, false, 0, false };
enum State { S_SPLASH, S_MENU, S_BROWSER, S_VIEWER, S_CONFIRM };
State appState = S_SPLASH;
// 0 = Read Files
// 1 = Delete Files
// 2 = WiFi toggle
#define MENU_COUNT 3
int menuIdx = 0;
bool deleteMode = false;
String menuLabel(int i) {
switch (i) {
case 0: return "Read Files";
case 1: return "Delete Files";
case 2: return wifiEnabled ? "WiFi:ON(tap=off)" : "WiFi:OFF(tap=on)";
}
return "";
}
// ─── Browser ──────────────────────────────────────────────────
String currentDir = "/";
std::vector<String> entries;
int cursorIdx = 0;
int viewOffset = 0;
#define ROWS_VISIBLE 4
#define ROW_H 13
#define HEADER_H 12
std::vector<String> selectedPaths;
enum ConfirmFocus { CF_DELETE, CF_CANCEL };
ConfirmFocus confirmFocus = CF_DELETE;
String openFilePath = "";
std::vector<String> fileLines;
int lineScroll = 0;
File uploadFileHandle;
String uploadDestDir = "/";
String htmlEsc(const String& s) {
String r = s;
r.replace("&", "&");
r.replace("<", "<");
r.replace(">", ">");
r.replace("\"", """);
return r;
}
String baseName(const String& p) {
int i = p.lastIndexOf('/');
return (i < 0) ? p : p.substring(i + 1);
}
String parentDir(const String& p) {
if (p == "/") return "/";
int i = p.lastIndexOf('/');
if (i <= 0) return "/";
return p.substring(0, i);
}
String joinPath(const String& dir, const String& name) {
if (dir == "/") return "/" + name;
return dir + "/" + name;
}
String humanSize(long bytes) {
if (bytes < 1024) return String(bytes) + "B";
if (bytes < 1048576) return String(bytes / 1024) + "K";
return String(bytes / 1048576) + "M";
}
bool sdDeleteRecursive(const String& path) {
Serial.println("DEL: " + path);
File f = SD.open(path);
if (!f) { Serial.println(" OPEN FAIL"); return false; }
if (f.isDirectory()) {
std::vector<String> children;
File child = f.openNextFile();
while (child) {
String cn = String(child.name());
Serial.println(" CHILD: [" + cn + "]");
children.push_back(cn);
child.close();
child = f.openNextFile();
}
f.close();
Serial.println(" children: " + String(children.size()));
for (auto& cp : children) {
// child.name() on ESP32 SD may be just filename OR full path — handle both
String fp = cp.startsWith("/") ? cp : ((path == "/") ? "/" + cp : path + "/" + cp);
Serial.println(" RECURSE: " + fp);
sdDeleteRecursive(fp);
}
bool ok = SD.rmdir(path.c_str());
Serial.println(" rmdir [" + path + "] = " + String(ok));
return ok;
}
f.close();
bool ok = SD.remove(path.c_str());
Serial.println(" remove [" + path + "] = " + String(ok));
return ok;
}
void wifiStart() {
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_SSID, AP_PASS);
delay(300);
server.begin();
wifiEnabled = true;
Serial.println("WiFi AP started");
}
void wifiStop() {
server.stop();
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_OFF);
wifiEnabled = false;
Serial.println("WiFi AP stopped");
}
void oledHeader(const String& title) {
oled.fillRect(0, 0, OLED_W, HEADER_H, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
oled.setTextSize(1);
oled.setCursor(2, 2);
String t = title.length() > 20 ? "~" + title.substring(title.length() - 19) : title;
oled.print(t);
oled.setTextColor(SSD1306_WHITE);
}
void oledSplash(const String& line1, const String& line2 = "", int holdMs = 0) {
oled.clearDisplay();
oled.setTextSize(1);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(0, 16);
oled.println(line1);
if (line2.length()) { oled.setCursor(0, 28); oled.println(line2); }
oled.display();
if (holdMs > 0) delay(holdMs);
}
// ═══════════════════════════════════════════════════════════════
// MAIN MENU — OLED
// ═══════════════════════════════════════════════════════════════
void menuDraw() {
oled.clearDisplay();
oled.fillRect(0, 0, 128, 12, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
oled.setTextSize(1);
oled.setCursor(28, 2);
oled.print("CheatCode");
oled.setTextColor(SSD1306_WHITE);
for (int i = 0; i < MENU_COUNT; i++) {
int y = 14 + i * 16;
bool sel = (i == menuIdx);
if (sel) {
oled.fillRoundRect(2, y - 1, 124, 14, 2, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
} else {
oled.setTextColor(SSD1306_WHITE);
}
oled.setCursor(6, y + 1);
oled.print(sel ? ">" : " ");
oled.print(" ");
String lbl = menuLabel(i);
if (lbl.length() > 18) lbl = lbl.substring(0, 17) + "~";
oled.print(lbl);
}
oled.setTextColor(SSD1306_WHITE);
oled.display();
}
void browserLoad(const String& path) {
currentDir = path;
cursorIdx = 0;
viewOffset = 0;
entries.clear();
File dir = SD.open(path);
if (!dir || !dir.isDirectory()) return;
std::vector<String> dirs, files;
File f = dir.openNextFile();
while (f) {
String n = baseName(String(f.name()));
if (n.length() > 0) {
if (f.isDirectory()) dirs.push_back(n + "/");
else files.push_back(n);
}
f.close();
f = dir.openNextFile();
}
dir.close();
std::sort(dirs.begin(), dirs.end());
std::sort(files.begin(), files.end());
if (path != "/") entries.push_back("../");
for (auto& d : dirs) entries.push_back(d);
for (auto& ff : files) entries.push_back(ff);
}
bool isPathSelected(int idx) {
if (idx < 0 || idx >= (int)entries.size()) return false;
String name = entries[idx];
if (name == "../") return false;
if (name.endsWith("/")) name = name.substring(0, name.length() - 1);
String fp = joinPath(currentDir, name);
return std::find(selectedPaths.begin(), selectedPaths.end(), fp) != selectedPaths.end();
}
void togglePathSelection(int idx) {
if (idx < 0 || idx >= (int)entries.size()) return;
String name = entries[idx];
if (name == "../") return;
if (name.endsWith("/")) name = name.substring(0, name.length() - 1);
String fp = joinPath(currentDir, name);
auto it = std::find(selectedPaths.begin(), selectedPaths.end(), fp);
if (it != selectedPaths.end()) selectedPaths.erase(it);
else selectedPaths.push_back(fp);
}
void browserDraw() {
oled.clearDisplay();
if (cursorIdx < viewOffset) viewOffset = cursorIdx;
if (cursorIdx >= viewOffset + ROWS_VISIBLE) viewOffset = cursorIdx - ROWS_VISIBLE + 1;
String hdrTitle = deleteMode ? ("[DEL] " + currentDir) : currentDir;
oledHeader(hdrTitle);
if (deleteMode && !selectedPaths.empty()) {
String badge = String(selectedPaths.size()) + " sel";
int bx = OLED_W - (int)badge.length() * 6 - 3;
oled.setTextColor(SSD1306_BLACK);
oled.setCursor(bx, 2);
oled.print(badge);
oled.setTextColor(SSD1306_WHITE);
}
if (entries.empty()) {
oled.setCursor(4, 18);
oled.print("(empty folder)");
oled.display();
return;
}
for (int i = 0; i < ROWS_VISIBLE; i++) {
int idx = viewOffset + i;
if (idx >= (int)entries.size()) break;
int y = HEADER_H + 1 + i * ROW_H;
bool sel = (idx == cursorIdx);
bool marked = deleteMode && isPathSelected(idx);
if (sel) {
oled.fillRoundRect(0, y - 1, 124, ROW_H, 2, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
} else {
oled.setTextColor(SSD1306_WHITE);
}
if (deleteMode) {
oled.drawRect(2, y + 1, 7, 7, sel ? SSD1306_BLACK : SSD1306_WHITE);
if (marked) oled.fillRect(3, y + 2, 5, 5, sel ? SSD1306_BLACK : SSD1306_WHITE);
oled.setCursor(12, y + 1);
} else {
oled.setCursor(3, y + 1);
}
String name = entries[idx];
bool isDir = name.endsWith("/");
String label = name;
if (label.length() > 17) label = label.substring(0, 16) + "~";
oled.print(isDir ? "\x10 " : " ");
oled.print(label);
}
oled.setTextColor(SSD1306_WHITE);
if ((int)entries.size() > ROWS_VISIBLE) {
int totalH = 64 - HEADER_H;
int barH = max(4, totalH * ROWS_VISIBLE / (int)entries.size());
int barY = HEADER_H + totalH * viewOffset / (int)entries.size();
oled.drawFastVLine(126, HEADER_H, totalH, SSD1306_WHITE);
oled.fillRect(125, barY, 3, barH, SSD1306_WHITE);
}
oled.display();
}
void browserEnter() {
if (entries.empty()) return;
String sel = entries[cursorIdx];
if (sel == "../") {
browserLoad(parentDir(currentDir));
appState = S_BROWSER;
browserDraw();
return;
}
bool isDir = sel.endsWith("/");
if (isDir) {
String dirName = sel.substring(0, sel.length() - 1);
String fullPath = joinPath(currentDir, dirName);
if (deleteMode) {
auto it = std::find(selectedPaths.begin(), selectedPaths.end(), fullPath);
if (it == selectedPaths.end()) {
selectedPaths.push_back(fullPath);
browserDraw();
} else {
selectedPaths.erase(it);
browserLoad(fullPath);
browserDraw();
}
} else {
browserLoad(fullPath);
browserDraw();
}
return;
}
// ── FILE ─────────────────────────────────────────────────────
if (deleteMode) {
togglePathSelection(cursorIdx);
browserDraw();
} else {
viewerOpen(joinPath(currentDir, sel));
}
}
void confirmDraw() {
oled.clearDisplay();
oled.fillRect(0, 0, OLED_W, HEADER_H, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
oled.setTextSize(1);
oled.setCursor(3, 2);
oled.print("Confirm Delete");
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(0, 14);
oled.print("Delete ");
oled.print(selectedPaths.size());
oled.print(" item(s):");
for (int i = 0; i < (int)selectedPaths.size() && i < 2; i++) {
oled.setCursor(4, 23 + i * 9);
String nm = baseName(selectedPaths[i]);
if (nm.length() > 17) nm = nm.substring(0, 16) + "~";
oled.print(nm);
}
if ((int)selectedPaths.size() > 2) {
oled.setCursor(4, 41);
oled.print("+ ");
oled.print(selectedPaths.size() - 2);
oled.print(" more...");
}
if (confirmFocus == CF_DELETE) {
oled.fillRoundRect(2, 50, 52, 13, 2, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
oled.setCursor(7, 53); oled.print("DELETE");
oled.setTextColor(SSD1306_WHITE);
oled.drawRoundRect(70, 50, 52, 13, 2, SSD1306_WHITE);
oled.setCursor(75, 53); oled.print("CANCEL");
} else {
oled.drawRoundRect(2, 50, 52, 13, 2, SSD1306_WHITE);
oled.setCursor(7, 53); oled.print("DELETE");
oled.fillRoundRect(70, 50, 52, 13, 2, SSD1306_WHITE);
oled.setTextColor(SSD1306_BLACK);
oled.setCursor(75, 53); oled.print("CANCEL");
oled.setTextColor(SSD1306_WHITE);
}
oled.display();
}
void confirmExecute() {
int count = 0;
for (const String& fp : selectedPaths) {
if (sdDeleteRecursive(fp)) count++;
}
selectedPaths.clear();
browserLoad(currentDir);
oledSplash("Done!", "Deleted " + String(count) + " item(s)", 900);
appState = S_BROWSER;
browserDraw();
}
void viewerOpen(const String& path) {
openFilePath = path;
fileLines.clear();
lineScroll = 0;
File f = SD.open(path);
if (!f || f.isDirectory()) return;
while (f.available()) {
String raw = f.readStringUntil('\n');
raw.replace("\r", "");
if (raw.length() == 0) { fileLines.push_back(""); continue; }
while (raw.length() > 0) {
fileLines.push_back(raw.substring(0, 21));
raw = raw.length() > 21 ? raw.substring(21) : "";
}
}
f.close();
if (fileLines.empty()) fileLines.push_back("(empty file)");
appState = S_VIEWER;
viewerDraw();
}
void viewerDraw() {
oled.clearDisplay();
oledHeader(baseName(openFilePath));
for (int i = 0; i < ROWS_VISIBLE; i++) {
int li = lineScroll + i;
if (li >= (int)fileLines.size()) break;
oled.setCursor(0, HEADER_H + 2 + i * ROW_H);
oled.setTextSize(1);
oled.setTextColor(SSD1306_WHITE);
oled.print(fileLines[li]);
}
if ((int)fileLines.size() > ROWS_VISIBLE) {
int total = ((int)fileLines.size() + ROWS_VISIBLE - 1) / ROWS_VISIBLE;
int cur = lineScroll / ROWS_VISIBLE + 1;
String pg = String(cur) + "/" + String(total);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(128 - (int)pg.length() * 6, 56);
oled.print(pg);
int totalH = 64 - HEADER_H;
int barH = max(4, totalH * ROWS_VISIBLE / (int)fileLines.size());
int barY = HEADER_H + totalH * lineScroll / (int)fileLines.size();
oled.drawFastVLine(126, HEADER_H, totalH, SSD1306_WHITE);
oled.fillRect(125, barY, 3, barH, SSD1306_WHITE);
}
oled.display();
}
void btnUpdate(Btn& b) {
b.shortPress = false;
b.longPress = false;
bool cur = (digitalRead(b.pin) == LOW);
bool prev = !b.prevState;
if (cur && !prev) {
b.pressedAt = millis();
b.longFired = false;
} else if (cur && !b.longFired) {
if (millis() - b.pressedAt >= BTN_LONGPRESS_MS) {
b.longPress = true;
b.longFired = true;
}
} else if (!cur && prev) {
unsigned long dur = millis() - b.pressedAt;
if (dur >= BTN_DEBOUNCE_MS && !b.longFired)
b.shortPress = true;
}
b.prevState = !cur;
}
void handleButtons() {
btnUpdate(btnUp);
btnUpdate(btnDown);
if (appState == S_MENU) {
if (btnUp.shortPress) { menuIdx = (menuIdx - 1 + MENU_COUNT) % MENU_COUNT; menuDraw(); }
if (btnDown.shortPress) { menuIdx = (menuIdx + 1) % MENU_COUNT; menuDraw(); }
if (btnUp.longPress) {
if (menuIdx == 0) {
deleteMode = false;
selectedPaths.clear();
browserLoad("/");
appState = S_BROWSER;
browserDraw();
} else if (menuIdx == 1) {
deleteMode = true;
selectedPaths.clear();
browserLoad("/");
appState = S_BROWSER;
browserDraw();
} else if (menuIdx == 2) {
if (wifiEnabled) {
wifiStop();
oledSplash("WiFi OFF", "AP disabled", 800);
} else {
wifiStart();
IPAddress ip = WiFi.softAPIP();
oledSplash("WiFi ON", ip.toString(), 1200);
}
menuDraw();
}
}
}
else if (appState == S_BROWSER) {
if (btnUp.shortPress) {
if (!entries.empty()) {
cursorIdx = (cursorIdx - 1 + (int)entries.size()) % (int)entries.size();
browserDraw();
}
}
if (btnDown.shortPress) {
if (!entries.empty()) {
cursorIdx = (cursorIdx + 1) % (int)entries.size();
browserDraw();
}
}
if (btnUp.longPress) { browserEnter(); }
if (btnDown.longPress) {
if (deleteMode && !selectedPaths.empty()) {
confirmFocus = CF_DELETE;
appState = S_CONFIRM;
confirmDraw();
} else if (currentDir != "/") {
browserLoad(parentDir(currentDir));
browserDraw();
} else {
selectedPaths.clear();
deleteMode = false;
appState = S_MENU;
menuDraw();
}
}
}
// ── CONFIRM ──────────────────────────────────────────────────
else if (appState == S_CONFIRM) {
if (btnUp.shortPress || btnDown.shortPress) {
confirmFocus = (confirmFocus == CF_DELETE) ? CF_CANCEL : CF_DELETE;
confirmDraw();
}
if (btnUp.longPress) {
if (confirmFocus == CF_DELETE) confirmExecute();
else { appState = S_BROWSER; browserDraw(); }
}
if (btnDown.longPress) { appState = S_BROWSER; browserDraw(); }
}
else if (appState == S_VIEWER) {
if (btnUp.shortPress) { if (lineScroll > 0) { lineScroll--; viewerDraw(); } }
if (btnDown.shortPress) {
if (lineScroll + ROWS_VISIBLE < (int)fileLines.size()) { lineScroll++; viewerDraw(); }
}
if (btnUp.longPress) { lineScroll = 0; viewerDraw(); }
if (btnDown.longPress) { appState = S_BROWSER; browserDraw(); }
}
}
String buildWebPage(const String& path) {
String html = F(R"RAW(<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CheatCode</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&display=swap');
*{box-sizing:border-box;margin:0;padding:0}
:root{
--bg:#080c10;--surface:#0f1419;--surface2:#161d27;
--border:#1e2d3d;--accent:#4af;--accent2:#2af098;
--text:#c9d1d9;--muted:#556066;--danger:#f85149;
--success:#3fb950;--warn:#e3b341;
}
body{font-family:'JetBrains Mono',monospace;background:var(--bg);color:var(--text);min-height:100vh}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
.topbar{
display:flex;align-items:center;gap:16px;
background:var(--surface);border-bottom:1px solid var(--border);
padding:12px 24px;position:sticky;top:0;z-index:100;
}
.logo{font-size:1.1rem;font-weight:700;color:var(--accent);letter-spacing:.05em}
.logo span{color:var(--accent2)}
.breadcrumb{display:flex;align-items:center;gap:4px;font-size:.8rem;color:var(--muted)}
.breadcrumb a{color:var(--text)}
.breadcrumb .sep{color:var(--border)}
.topbar .spacer{flex:1}
.badge{background:var(--surface2);border:1px solid var(--border);border-radius:4px;padding:3px 8px;font-size:.7rem;color:var(--muted)}
.container{max-width:900px;margin:0 auto;padding:24px 16px}
.toolbar{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center}
.input{flex:1;min-width:160px;background:var(--surface2);border:1px solid var(--border);color:var(--text);padding:8px 12px;border-radius:6px;font-family:inherit;font-size:.85rem;}
.input:focus{outline:none;border-color:var(--accent)}
.btn{font-family:inherit;font-size:.8rem;border:1px solid var(--border);border-radius:6px;padding:7px 14px;cursor:pointer;transition:all .15s;white-space:nowrap;}
.btn-primary{background:var(--accent);color:#000;border-color:var(--accent)}
.btn-primary:hover{filter:brightness(1.15)}
.btn-ghost{background:var(--surface2);color:var(--text)}
.btn-ghost:hover{border-color:var(--accent);color:var(--accent)}
.btn-danger{background:transparent;color:var(--danger);border-color:var(--danger)}
.btn-danger:hover{background:var(--danger);color:#000}
.btn-sm{padding:4px 10px;font-size:.75rem}
.dropzone{border:2px dashed var(--border);border-radius:10px;background:var(--surface);padding:28px 20px;text-align:center;transition:all .2s;cursor:pointer;margin-bottom:16px;position:relative;}
.dropzone.over{border-color:var(--accent);background:rgba(68,170,255,.07)}
.dropzone input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.dropzone .dz-icon{font-size:2rem;margin-bottom:8px}
.dropzone .dz-label{font-size:.9rem;color:var(--muted)}
.dropzone .dz-sub{font-size:.75rem;color:var(--muted);margin-top:4px}
.progress-wrap{display:none;margin-top:12px}
.progress-bar{background:var(--surface2);border-radius:4px;height:6px;overflow:hidden}
.progress-fill{background:var(--accent);height:100%;width:0%;transition:width .2s}
.progress-label{font-size:.75rem;color:var(--muted);margin-top:5px}
.file-panel{background:var(--surface);border:1px solid var(--border);border-radius:10px;overflow:hidden}
.file-head{display:grid;grid-template-columns:1fr 70px 90px;padding:8px 16px;font-size:.72rem;color:var(--muted);border-bottom:1px solid var(--border);background:var(--surface2);}
.file-row{display:grid;grid-template-columns:1fr 70px 90px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--border);transition:background .12s;}
.file-row:last-child{border-bottom:none}
.file-row:hover{background:var(--surface2)}
.file-name{display:flex;align-items:center;gap:8px;overflow:hidden}
.file-name .icon{font-size:1.1rem;flex-shrink:0}
.file-name .name-link{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.85rem;color:var(--text);}
.file-name .name-link:hover{color:var(--accent)}
.file-size{font-size:.78rem;color:var(--muted);text-align:right}
.file-actions{display:flex;justify-content:flex-end;gap:4px}
.empty{padding:40px;text-align:center;color:var(--muted);font-size:.85rem}
.toast{position:fixed;bottom:24px;right:24px;background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:10px 16px;font-size:.82rem;opacity:0;transform:translateY(12px);transition:all .25s;pointer-events:none;z-index:999;}
.toast.show{opacity:1;transform:translateY(0)}
.toast.ok{border-color:var(--success);color:var(--success)}
.toast.err{border-color:var(--danger);color:var(--danger)}
@media(max-width:600px){.file-head,.file-row{grid-template-columns:1fr 80px}.file-size{display:none}}
</style>
</head><body>
)RAW");
html += "<div class='topbar'>";
html += "<div class='logo'>📝 Cheat<span>Code</span></div>";
html += "<div class='breadcrumb'><a href='/?path=/'>root</a>";
if (path != "/") {
String acc = "";
String tmp = path.substring(1);
while (tmp.length()) {
int sl = tmp.indexOf('/');
String seg = (sl < 0) ? tmp : tmp.substring(0, sl);
acc += "/" + seg;
html += "<span class='sep'>/</span><a href='/?path=" + acc + "'>" + htmlEsc(seg) + "</a>";
if (sl < 0) break;
tmp = tmp.substring(sl + 1);
}
}
html += "</div><div class='spacer'></div>";
html += "<div class='badge'>192.168.4.1</div></div>";
html += "<div class='container'>";
html += R"RAW(<div class='toolbar'>
<input class='input' id='dname' placeholder='New folder name…' onkeydown="if(event.key==='Enter')mkDir()">
<button class='btn btn-primary' onclick='mkDir()'>+ Folder</button>
</div>)RAW";
html += R"RAW(<div class='dropzone' id='dz'>
<input type='file' id='fup' multiple onchange='uploadFiles(this.files)'>
<div class='dz-icon'>⬆</div>
<div class='dz-label'>Drop files here or click to upload</div>
<div class='dz-sub'>Uploads go to the current folder</div>
<div class='progress-wrap' id='pwrap'>
<div class='progress-bar'><div class='progress-fill' id='pfill'></div></div>
<div class='progress-label' id='plab'>Uploading…</div>
</div>
</div>)RAW";
html += "<div class='file-panel'>";
html += "<div class='file-head'><span>Name</span><span style='text-align:right'>Size</span><span style='text-align:right'>Actions</span></div>";
if (path != "/") {
String par = parentDir(path);
html += "<div class='file-row'><div class='file-name'><span class='icon'>📂</span>"
"<a class='name-link' href='/?path=" + par + "'>..</a></div>"
"<div class='file-size'>—</div><div class='file-actions'></div></div>";
}
File dir = SD.open(path);
bool hasEntries = false;
if (dir) {
for (int pass = 0; pass < 2; pass++) {
dir.rewindDirectory();
File f = dir.openNextFile();
while (f) {
bool isDir = f.isDirectory();
if ((pass == 0 && !isDir) || (pass == 1 && isDir)) { f.close(); f = dir.openNextFile(); continue; }
String fname = baseName(String(f.name()));
if (fname.length() == 0) { f.close(); f = dir.openNextFile(); continue; }
hasEntries = true;
String fp = joinPath(path, fname);
String szStr = isDir ? "—" : humanSize(f.size());
String icon = isDir ? "📁" : "📄";
String href = isDir ? ("/?path=" + fp) : ("/view?path=" + fp);
html += "<div class='file-row'><div class='file-name'><span class='icon'>" + icon + "</span>"
"<a class='name-link' href='" + href + "'>" + htmlEsc(fname) + "</a></div>";
html += "<div class='file-size'>" + szStr + "</div>";
html += "<div class='file-actions'>";
if (!isDir) html += "<a href='/dl?path=" + fp + "'><button class='btn btn-ghost btn-sm' title='Download'>↓</button></a>";
html += "<button class='btn btn-danger btn-sm' onclick=\"delItem('" + htmlEsc(fp) + "'," + (isDir ? "true" : "false") + ")\" title='Delete'>✕</button>";
html += "</div></div>";
f.close();
f = dir.openNextFile();
}
}
dir.close();
}
if (!hasEntries && path == "/") {
html += "<div class='empty'>No files yet. Upload something!</div>";
}
html += "</div></div>";
html += "<div class='toast' id='toast'></div>";
html += R"RAW(<script>
const CUR_PATH = ")RAW" + htmlEsc(path) + R"RAW(";
function toast(msg,type='ok'){
const t=document.getElementById('toast');
t.textContent=msg;t.className='toast '+type+' show';
setTimeout(()=>t.className='toast',2400);
}
function mkDir(){
const n=document.getElementById('dname').value.trim();
if(!n)return;
fetch('/mkdir?path='+encodeURIComponent(CUR_PATH+'/'+n))
.then(r=>r.ok?toast('Folder created'):toast('Error','err'))
.then(()=>setTimeout(()=>location.reload(),600));
}
function delItem(fp,isDir){
const label=isDir?'folder and ALL its contents':'file';
if(!confirm('Delete this '+label+'?\n'+fp))return;
fetch('/delete?path='+encodeURIComponent(fp))
.then(r=>r.ok?toast('Deleted'):toast('Error','err'))
.then(()=>setTimeout(()=>location.reload(),600));
}
function uploadFiles(files){
if(!files.length)return;
const pwrap=document.getElementById('pwrap');
const pfill=document.getElementById('pfill');
const plab=document.getElementById('plab');
pwrap.style.display='block';
let done=0;
function next(i){
if(i>=files.length){
toast('Upload complete ✓');
setTimeout(()=>location.reload(),800);
return;
}
const file=files[i];
const fd=new FormData();
fd.append('file',file);
plab.textContent='Uploading '+file.name+' ('+(i+1)+'/'+files.length+')';
const xhr=new XMLHttpRequest();
xhr.open('POST','/upload?dir='+encodeURIComponent(CUR_PATH));
xhr.upload.onprogress=e=>{
const pct=((done+e.loaded/e.total)/files.length)*100;
pfill.style.width=pct.toFixed(1)+'%';
};
xhr.onload=()=>{
if(xhr.status===200){ done++; next(i+1); }
else toast('Upload failed: '+file.name,'err');
};
xhr.onerror=()=>toast('Upload failed: '+file.name,'err');
xhr.send(fd);
}
next(0);
}
const dz=document.getElementById('dz');
['dragenter','dragover'].forEach(e=>dz.addEventListener(e,ev=>{ev.preventDefault();dz.classList.add('over');}));
['dragleave','drop'].forEach(e=>dz.addEventListener(e,ev=>{
ev.preventDefault();dz.classList.remove('over');
if(ev.type==='drop')uploadFiles(ev.dataTransfer.files);
}));
</script></body></html>
)RAW";
return html;
}
void webRoot() {
String path = server.hasArg("path") ? server.arg("path") : "/";
if (!path.startsWith("/")) path = "/" + path;
server.send(200, "text/html", buildWebPage(path));
}
void webMkdir() {
if (server.hasArg("path")) {
SD.mkdir(server.arg("path").c_str());
if (appState == S_BROWSER) { browserLoad(currentDir); browserDraw(); }
}
server.send(200, "text/plain", "OK");
}
void webDelete() {
if (server.hasArg("path")) {
sdDeleteRecursive(server.arg("path"));
if (appState == S_BROWSER) { browserLoad(currentDir); browserDraw(); }
}
server.send(200, "text/plain", "OK");
}
void webUploadDone() {
server.send(200, "text/plain", "OK");
}
void webUploadHandler() {
HTTPUpload& up = server.upload();
if (up.status == UPLOAD_FILE_START) {
uploadDestDir = server.hasArg("dir") ? server.arg("dir") : "/";
if (!uploadDestDir.startsWith("/")) uploadDestDir = "/" + uploadDestDir;
if (!SD.exists(uploadDestDir.c_str())) SD.mkdir(uploadDestDir.c_str());
String dest = joinPath(uploadDestDir, up.filename);
Serial.println("Upload START → " + dest);
uploadFileHandle = SD.open(dest, FILE_WRITE);
if (!uploadFileHandle) Serial.println("Upload OPEN FAIL: " + dest);
} else if (up.status == UPLOAD_FILE_WRITE) {
if (uploadFileHandle) uploadFileHandle.write(up.buf, up.currentSize);
} else if (up.status == UPLOAD_FILE_END) {
if (uploadFileHandle) {
uploadFileHandle.close();
Serial.println("Upload END → " + String(up.totalSize) + " bytes");
}
if (appState == S_BROWSER) { browserLoad(currentDir); browserDraw(); }
}
}
void webView() {
if (!server.hasArg("path")) { server.send(400, "text/plain", "Missing path"); return; }
String path = server.arg("path");
File f = SD.open(path);
if (!f || f.isDirectory()) { server.send(404, "text/plain", "Not found"); return; }
String fname = baseName(path);
String html =
"<!DOCTYPE html><html><head>"
"<meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1'>"
"<title>" + htmlEsc(fname) + "</title>"
"<style>"
"@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&display=swap');"
"*{box-sizing:border-box;margin:0;padding:0}"
"body{font-family:'JetBrains Mono',monospace;background:#080c10;color:#c9d1d9;min-height:100vh}"
".topbar{background:#0f1419;border-bottom:1px solid #1e2d3d;padding:12px 20px;display:flex;gap:12px;align-items:center;position:sticky;top:0}"
".logo{color:#4af;font-weight:700}a{color:#4af;text-decoration:none}"
".btn{background:#161d27;color:#c9d1d9;border:1px solid #1e2d3d;border-radius:6px;padding:6px 14px;cursor:pointer;font-family:inherit;font-size:.8rem}"
".btn:hover{border-color:#4af;color:#4af}"
".fname{color:#3fb950;font-size:.85rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}"
".viewer-wrap{max-width:900px;margin:24px auto;padding:0 16px}"
".viewer-panel{background:#0f1419;border:1px solid #1e2d3d;border-radius:10px;overflow:hidden}"
".viewer-stats{padding:8px 16px;border-bottom:1px solid #1e2d3d;background:#161d27;font-size:.75rem;color:#556066}"
"pre{padding:20px 16px;white-space:pre-wrap;word-break:break-all;font-size:.83rem;line-height:1.8}"
"</style></head><body>"
"<div class='topbar'><span class='logo'>📝</span>"
"<button class='btn' onclick='history.back()'>← Back</button>"
"<span class='fname'>" + htmlEsc(path) + "</span></div>"
"<div class='viewer-wrap'><div class='viewer-panel'>"
"<div class='viewer-stats' id='stats'>Loading…</div>"
"<pre>";
long lines = 0, chars = 0;
while (f.available()) {
String line = f.readStringUntil('\n');
html += htmlEsc(line) + "\n";
lines++;
chars += line.length();
}
f.close();
html += "</pre></div></div>";
html += "<script>document.getElementById('stats').textContent='"
+ String(lines) + " lines · " + String(chars) + " chars · " + htmlEsc(baseName(path)) + "';</script>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void webDownload() {
if (!server.hasArg("path")) { server.send(400, "text/plain", "Missing path"); return; }
String path = server.arg("path");
File f = SD.open(path);
if (!f || f.isDirectory()) { server.send(404, "text/plain", "Not found"); return; }
server.sendHeader("Content-Disposition", "attachment; filename=\"" + baseName(path) + "\"");
server.streamFile(f, "application/octet-stream");
f.close();
}
// ═══════════════════════════════════════════════════════════════
// SETUP
// ═══════════════════════════════════════════════════════════════
void setup() {
Serial.begin(115200);
delay(200);
Serial.println("\n=== CheatCode v2 Boot ===");
pinMode(PIN_BTN_UP, INPUT_PULLUP);
pinMode(PIN_BTN_DOWN, INPUT_PULLUP);
Wire.begin(PIN_OLED_SDA, PIN_OLED_SCL);
if (!oled.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("[FATAL] OLED init failed");
while (1) delay(100);
}
oled.setTextSize(1);
oled.setTextColor(SSD1306_WHITE);
oled.clearDisplay();
oled.clearDisplay();
oled.setTextSize(1);
oled.setCursor(24, 10); oled.print("CheatCode v2");
oled.drawFastHLine(0, 20, 128, SSD1306_WHITE);
oled.setCursor(10, 28); oled.print("by ESP32 + SD");
oled.setCursor(28, 40); oled.print("Booting...");
oled.display();
delay(1200);
oledSplash("Mounting SD card...");
// CUSTOM SPI INIT (MISO → GPIO2)
SPI.begin(PIN_SD_SCK, PIN_SD_MISO, PIN_SD_MOSI, PIN_SD_CS);
if (!SD.begin(PIN_SD_CS)) {
oledSplash("SD CARD FAIL!", "Check wiring!", 3000);
Serial.println("[FATAL] SD card mount failed");
while (1) delay(100);
}
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.printf("SD: %llu MB\n", cardSize);
oledSplash("SD OK", String(cardSize) + " MB", 600);
oledSplash("Starting WiFi AP...");
WiFi.mode(WIFI_AP);