-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.c
More file actions
3839 lines (3568 loc) · 201 KB
/
main.c
File metadata and controls
3839 lines (3568 loc) · 201 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 "vtree.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <sys/statvfs.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <pthread.h>
// ---------------------------------------------------------------------------
// Version
// ---------------------------------------------------------------------------
#define VTREE_VERSION "1.4.3"
// ---------------------------------------------------------------------------
// Globals
// ---------------------------------------------------------------------------
AppConfig cfg;
AppState panes[2];
int active_pane = 0;
AppMode current_mode = MODE_EXPLORER;
bool debug_mode = false;
FILE *debug_log_file = NULL;
char configfile[MAX_PATH] = {0};
// ---------------------------------------------------------------------------
// Logging — writes to stdout + optional log file, with a wall-clock timestamp.
// Uses SDL_GetTicks() (ms since SDL_Init); shows 0 for the two pre-init lines.
// Only emits output when debug_mode is true.
// ---------------------------------------------------------------------------
void vtree_log(const char *fmt, ...) {
if (!debug_mode) return;
Uint32 ms = SDL_GetTicks();
char ts[20];
snprintf(ts, sizeof(ts), "[%4u.%03u] ", (unsigned)(ms / 1000), (unsigned)(ms % 1000));
va_list ap;
va_start(ap, fmt); fputs(ts, stdout); vprintf(fmt, ap); va_end(ap);
if (debug_log_file) {
va_start(ap, fmt);
fputs(ts, debug_log_file); vfprintf(debug_log_file, fmt, ap);
fflush(debug_log_file);
va_end(ap);
}
}
bool delete_confirm_active = false;
bool paste_conflict_active = false;
int paste_conflict_sel = 0; // selected option in conflict modal
int paste_conflict_count = 0; // how many clipboard items conflict
bool paste_dest_active = false;
int paste_dest_sel = 0; // 0 = left pane, 1 = right pane
int paste_dest_pane = 0; // resolved destination pane index
// Background paste (copy/move) thread
static pthread_t paste_tid;
static volatile bool paste_running = false;
volatile bool paste_abort = false; // extern in vtree.h — read by fileop.c
static volatile bool paste_done = false;
static int paste_prog_cur = 0; // clipboard items completed so far
static int paste_prog_total = 0; // total clipboard items
char paste_prog_name[MAX_PATH]; // current filename (updated per-file deep in copy_path_r)
volatile long long paste_bytes_done = 0; // extern in vtree.h — updated by copy_file_data
volatile long long paste_bytes_total = 0; // extern in vtree.h — set by copy_file_data
volatile int paste_files_done = 0; // extern in vtree.h — files completed (not items)
volatile int paste_files_total = 0; // extern in vtree.h — total files to copy
char paste_copy_root[MAX_PATH]; // extern in vtree.h — root path for display
static bool do_symlink_after_dest = false; // dest chooser is for symlink, not paste
int settings_index = 0;
Clipboard clip = { .op = OP_NONE, .count = 0 };
GlyphEntry glyph_cache[GLYPH_CACHE_SIZE];
Uint32 glyph_frame = 0;
// Top-level menu
#define TOPMENU_FILES 0
#define TOPMENU_SETTINGS 1
#define TOPMENU_DISKINFO 2
#define TOPMENU_ABOUT 3
#define TOPMENU_EXIT 4
#define TOPMENU_MAX 5
static const char *topmenu_items[TOPMENU_MAX] = { "Menu_Files", "Menu_Settings", "Menu_DiskInfo", "Menu_About", "Menu_Exit" };
// File-ops submenu
#define FILEMENU_COPY 0
#define FILEMENU_CUT 1
#define FILEMENU_PASTE 2
#define FILEMENU_SYMLINK 3
#define FILEMENU_RENAME 4
#define FILEMENU_DELETE 5
#define FILEMENU_NEWFILE 6
#define FILEMENU_NEWDIR 7
#define FILEMENU_BACK 8
#define FILEMENU_MAX 9
static const char *filemenu_items[FILEMENU_MAX] = {
"FileOp_Copy", "FileOp_Cut", "FileOp_Paste", "FileOp_Symlink",
"FileOp_Rename", "FileOp_Delete", "FileOp_NewFile", "FileOp_NewFolder", "FileOp_Back"
};
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_GameController *pad = NULL;
static int phys_w = 0, phys_h = 0; // physical display dims (set once at startup)
static SDL_Texture *render_target = NULL; // off-screen target for rotation; NULL = no rotation
TTF_Font *font_list = NULL, *font_header = NULL, *font_footer = NULL, *font_menu = NULL, *font_hex = NULL;
SDL_Texture *tex_file = NULL, *tex_folder = NULL;
SDL_Texture *tex_img = NULL, *tex_txt = NULL, *tex_dirup = NULL;
SDL_Texture *tex_copy = NULL, *tex_cut = NULL, *tex_paste = NULL, *tex_symlink = NULL;
SDL_Texture *tex_rename = NULL, *tex_delete = NULL, *tex_settings = NULL, *tex_exit = NULL;
SDL_Texture *tex_newfile = NULL, *tex_newfolder = NULL, *tex_about = NULL, *tex_diskinfo = NULL;
SDL_Texture *tex_enterfol = NULL;
SDL_Texture *tex_viewer = NULL, *tex_hexview = NULL, *tex_imgview = NULL, *tex_fileinfo = NULL, *tex_exec = NULL;
SDL_Texture *tex_logo = NULL;
// ---------------------------------------------------------------------------
// Font file list — populated by scan_fonts() at startup
// ---------------------------------------------------------------------------
#define MAX_FONT_FILES 64
static char font_files[MAX_FONT_FILES][MAX_PATH];
static int font_file_count = 0;
static int current_font_idx = 0;
// Executable directory — resolved once, used for font path construction
char vtree_exe_dir[MAX_PATH] = "";
// Full resolved path of the currently active font — used by hexview auto-sizer
char vtree_font_path[MAX_PATH] = "";
static void init_exe_dir(void) {
char buf[MAX_PATH];
ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (len > 0) {
buf[len] = '\0';
char *sl = strrchr(buf, '/');
if (sl) { *sl = '\0'; copy_str(vtree_exe_dir, buf, sizeof(vtree_exe_dir)); return; }
}
strncpy(vtree_exe_dir, ".", MAX_PATH - 1);
}
static bool has_font_ext(const char *name) {
size_t nl = strlen(name);
if (nl < 5) return false;
const char *e = name + nl - 4;
char lc[5];
for (int i = 0; i < 4; i++) lc[i] = (char)tolower((unsigned char)e[i]);
lc[4] = '\0';
return strcmp(lc, ".ttf") == 0 || strcmp(lc, ".otf") == 0;
}
// Compare two font_files entries by basename for qsort
static int font_name_cmp(const void *a, const void *b) {
const char *ba = strrchr((const char *)a, '/'); ba = ba ? ba + 1 : (const char *)a;
const char *bb = strrchr((const char *)b, '/'); bb = bb ? bb + 1 : (const char *)b;
return strcmp(ba, bb);
}
static void scan_fonts(void) {
init_exe_dir();
font_file_count = 0;
// Scan fonts/ subdirectory next to the executable — the only font source
char fonts_dir[MAX_PATH];
snprintf(fonts_dir, MAX_PATH, "%s/fonts", vtree_exe_dir);
DIR *d = opendir(fonts_dir);
if (d) {
struct dirent *de;
while ((de = readdir(d)) && font_file_count < MAX_FONT_FILES) {
if (!has_font_ext(de->d_name)) continue;
snprintf(font_files[font_file_count++], MAX_PATH, "%s/%s", fonts_dir, de->d_name);
}
closedir(d);
}
// Sort all entries by basename
if (font_file_count > 1)
qsort(font_files, font_file_count, MAX_PATH, font_name_cmp);
// Match current_font_idx to cfg.font_path; if blank, use first available font
current_font_idx = 0;
if (cfg.font_path[0]) {
const char *want = strrchr(cfg.font_path, '/');
want = want ? want + 1 : cfg.font_path;
for (int i = 0; i < font_file_count; i++) {
const char *bn = strrchr(font_files[i], '/');
bn = bn ? bn + 1 : font_files[i];
if (strcmp(bn, want) == 0) { current_font_idx = i; break; }
}
}
// Keep the resolved full path in sync for hexview auto-sizer
if (font_file_count > 0)
copy_str(vtree_font_path, font_files[current_font_idx], sizeof(vtree_font_path));
}
// ---------------------------------------------------------------------------
// File-type detection
// ---------------------------------------------------------------------------
static bool is_text_file(const char *name) {
static const char *text_exts[] = {
".txt", ".md", ".cfg", ".ini", ".conf", ".log", ".lua", ".c", ".h",
".cpp", ".cc", ".py", ".sh", ".bash", ".json", ".xml", ".yaml", ".yml",
".csv", ".html", ".htm", ".css", ".js", ".ts", ".toml", ".rs", ".go",
".java", ".kt", ".swift", ".rb", ".pl", ".asm", ".s", ".nfo", ".me",
".readme", ".license", ".makefile", ".cmake", ".diff", ".patch",
NULL
};
const char *dot = strrchr(name, '.');
if (!dot) {
const char *textnames[] = { "makefile", "readme", "license", "authors",
"changelog", "copying", "install", NULL };
char lower[256]; int i = 0;
while (name[i] && i < 255) { lower[i] = (char)tolower((unsigned char)name[i]); i++; }
lower[i] = '\0';
for (int j = 0; textnames[j]; j++)
if (strcmp(lower, textnames[j]) == 0) return true;
return false;
}
char lower[32]; int i = 0;
while (dot[i] && i < 31) { lower[i] = (char)tolower((unsigned char)dot[i]); i++; }
lower[i] = '\0';
for (int j = 0; text_exts[j]; j++)
if (strcmp(lower, text_exts[j]) == 0) return true;
// Check extra extensions from config
for (int j = 0; j < cfg.extra_text_ext_count; j++)
if (strcmp(lower, cfg.extra_text_exts[j]) == 0) return true;
return false;
}
static bool is_image_file(const char *name) {
static const char *img_exts[] = {
".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tga", ".tiff", ".tif", ".webp", ".lbm",
".pnm", ".pbm", ".pgm", ".ppm", ".xcf", ".xpm", ".svg",
NULL
};
const char *dot = strrchr(name, '.');
if (!dot) return false;
char lower[32]; int i = 0;
while (dot[i] && i < 31) { lower[i] = (char)tolower((unsigned char)dot[i]); i++; }
lower[i] = '\0';
for (int j = 0; img_exts[j]; j++)
if (strcmp(lower, img_exts[j]) == 0) return true;
// Check extra extensions from config
for (int j = 0; j < cfg.extra_image_ext_count; j++)
if (strcmp(lower, cfg.extra_image_exts[j]) == 0) return true;
return false;
}
// ---------------------------------------------------------------------------
// Icon selection — returns the best matching texture for a file entry.
// Falls back gracefully: specific → tex_file → NULL.
// ---------------------------------------------------------------------------
static SDL_Texture *get_file_icon(const FileEntry *fe) {
if (fe->is_dir) {
if (strcmp(fe->name, "..") == 0)
return tex_dirup ? tex_dirup : tex_folder;
return tex_folder;
}
if (is_image_file(fe->name)) return tex_img ? tex_img : tex_file;
if (is_text_file(fe->name)) return tex_txt ? tex_txt : tex_file;
return tex_file;
}
// ---------------------------------------------------------------------------
// Action chooser — dynamic per file type
// ---------------------------------------------------------------------------
#define ACT_TEXT 0
#define ACT_HEX 1
#define ACT_IMG 2
#define ACT_INFO 3
#define ACT_CANCEL 4
#define ACT_EXEC 5
static const char *act_labels[] = { "ActionChooser_Text", "ActionChooser_Hex", "ActionChooser_Image", "ActionChooser_Info", "ActionChooser_Cancel", "ActionChooser_Execute" };
static int choose_actions[8]; // action IDs for current menu
static int choose_count = 0;
static int choose_selection = 0;
static int choose_default = 0; // index of the auto-selected "best" viewer
static char choose_path[MAX_PATH];
static bool choose_path_is_dir = false;
static int choose_marked = 0; // marked-file count in active pane at open_file() time
static int choose_pane = 0; // active pane at open_file() time
// ---------------------------------------------------------------------------
// File info modal
// ---------------------------------------------------------------------------
#define FILEINFO_MAX_LINES 8
static bool fileinfo_active = false;
// Disk info modal
#define DISKINFO_MAX_LINES 96
static char diskinfo_lines[DISKINFO_MAX_LINES][128];
static int diskinfo_bar_pct[DISKINFO_MAX_LINES]; // -1 = text line, 0-100 = draw bar
static int diskinfo_line_count = 0;
static int diskinfo_scroll = 0;
static int diskinfo_visible = 0;
// Drill-down state
static int diskinfo_mode = 0; // 0 = partition list, 1 = drill-down
static int diskinfo_sel_part = 0; // highlighted partition index (mode 0)
static int diskinfo_sel_dir = 0; // highlighted directory entry index (mode 1)
static char diskinfo_drillpath[256]; // current drill-down path
#define DISKINFO_DEPTH_MAX 16
static char diskinfo_pathstack[DISKINFO_DEPTH_MAX][256];
static int diskinfo_depth = 0;
static int diskinfo_part_lines[48]; // line index of each partition's header line
static int diskinfo_part_count = 0; // number of partitions
static char diskinfo_dir_paths[48][256]; // full paths of directory entries in drill-down
static int diskinfo_dir_count = 0; // number of directory entries in drill-down
// Parallel stacks: save cursor/scroll position at each depth level
static int diskinfo_selstack[DISKINFO_DEPTH_MAX];
static int diskinfo_scrollstack[DISKINFO_DEPTH_MAX];
// Scan result cache keyed by path
#define DISKINFO_CACHE_MAX 6
typedef struct {
char path[256];
char lines[DISKINFO_MAX_LINES][128];
int bar_pct[DISKINFO_MAX_LINES];
int line_count;
char dir_paths[48][256];
int dir_count;
bool valid;
} DiskinfoCacheEntry;
static DiskinfoCacheEntry diskinfo_cache[DISKINFO_CACHE_MAX];
static int diskinfo_cache_next = 0; // round-robin write pointer
// Background scan thread
static pthread_t diskinfo_scan_tid;
static volatile bool diskinfo_scanning = false;
static volatile bool diskinfo_scan_abort = false;
static volatile bool diskinfo_scan_ready = false;
static char diskinfo_scan_for_path[256];
static char diskinfo_scan_lines[DISKINFO_MAX_LINES][128];
static int diskinfo_scan_bar_pct[DISKINFO_MAX_LINES];
static int diskinfo_scan_line_count;
static char diskinfo_scan_dir_paths[48][256];
static int diskinfo_scan_dir_count;
static bool fileinfo_is_multi = false;
static bool fileinfo_is_dir = false;
static bool exec_error_active = false;
static char exec_error_title[64] = "Cannot Execute";
static char exec_error_msg[256] = "";
static char fileinfo_lines[FILEINFO_MAX_LINES][256];
static int fileinfo_line_count = 0;
static bool fs_supports_symlinks(const char *path) {
struct statfs sfs;
if (statfs(path, &sfs) != 0) return true; // assume yes on error
switch ((unsigned long)sfs.f_type) {
case 0x4D44UL: // MSDOS_SUPER_MAGIC — FAT12/FAT16/FAT32/vFAT
case 0x2011BAB0UL: // EXFAT_SUPER_MAGIC — exFAT (kernel driver)
case 0x65735546UL: // FUSEBLK_SUPER_MAGIC — FUSE block (fuse-exfat, NTFS-3g, etc.)
return false;
default:
return true;
}
}
static long long calc_dir_size(const char *path) {
long long total = 0;
DIR *d = opendir(path);
if (!d) return 0;
struct dirent *e;
while ((e = readdir(d))) {
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
char sub[MAX_PATH]; join_path(sub, path, e->d_name);
struct stat st;
if (lstat(sub, &st) == 0) {
if (S_ISDIR(st.st_mode)) total += calc_dir_size(sub);
else total += st.st_size;
}
}
closedir(d);
return total;
}
static void format_perms(mode_t m, char *out) {
out[0] = S_ISLNK(m) ? 'l' : S_ISDIR(m) ? 'd' : '-';
out[1] = (m & S_IRUSR) ? 'r' : '-'; out[2] = (m & S_IWUSR) ? 'w' : '-'; out[3] = (m & S_IXUSR) ? 'x' : '-';
out[4] = (m & S_IRGRP) ? 'r' : '-'; out[5] = (m & S_IWGRP) ? 'w' : '-'; out[6] = (m & S_IXGRP) ? 'x' : '-';
out[7] = (m & S_IROTH) ? 'r' : '-'; out[8] = (m & S_IWOTH) ? 'w' : '-'; out[9] = (m & S_IXOTH) ? 'x' : '-';
out[10] = '\0';
}
static void show_fileinfo(const char *path) {
fileinfo_line_count = 0;
struct stat lst, st;
if (lstat(path, &lst) != 0) {
snprintf(fileinfo_lines[fileinfo_line_count++], 256, "%s", tr("FileInfo_CannotStat"));
fileinfo_active = true;
return;
}
bool is_link = S_ISLNK(lst.st_mode);
struct stat *info = &lst;
bool target_ok = false;
if (is_link && stat(path, &st) == 0) { info = &st; target_ok = true; }
// Name
const char *base = strrchr(path, '/');
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Name"), base ? base + 1 : path);
// Size — for directories walk recursively, otherwise use stat size
char sz[32];
bool item_is_dir = S_ISDIR(info->st_mode);
long long item_size = item_is_dir ? calc_dir_size(path) : (long long)info->st_size;
format_size(item_size, sz);
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Size"), sz, item_size);
// Type
const char *ftype = is_link ? (target_ok ? (S_ISDIR(info->st_mode) ? tr("FileInfo_TypeSymlinkDir") : tr("FileInfo_TypeSymlinkFile")) : tr("FileInfo_TypeSymlinkBroken")) :
S_ISDIR(lst.st_mode) ? tr("FileInfo_TypeDirectory") : tr("FileInfo_TypeRegular");
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Type"), ftype);
// Permissions
char perms[12];
format_perms(lst.st_mode, perms);
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Perms"), perms, (unsigned)(lst.st_mode & 07777));
// Owner / group
char owner[64] = "", group[64] = "";
struct passwd *pw = getpwuid(lst.st_uid);
struct group *gr = getgrgid(lst.st_gid);
if (pw) snprintf(owner, sizeof(owner), "%s", pw->pw_name);
else snprintf(owner, sizeof(owner), "%u", lst.st_uid);
if (gr) snprintf(group, sizeof(group), "%s", gr->gr_name);
else snprintf(group, sizeof(group), "%u", lst.st_gid);
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Owner"), owner, group);
// Modified time
char tbuf[64];
struct tm *tm = localtime(&lst.st_mtime);
strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", tm);
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Modified"), tbuf);
// Symlink target
if (is_link) {
char target[MAX_PATH] = "";
ssize_t n = readlink(path, target, MAX_PATH - 1);
if (n > 0) { target[n] = '\0'; snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Target"), target); }
}
fileinfo_is_multi = false;
fileinfo_is_dir = item_is_dir;
fileinfo_active = true;
}
static void show_fileinfo_multi(void) {
fileinfo_line_count = 0;
int total = 0, nfiles = 0, ndirs = 0, nlinks = 0;
long long total_size = 0;
int np = cfg.single_pane ? 1 : 2;
for (int p = 0; p < np; p++) {
AppState *s = &panes[p];
for (int i = 0; i < s->file_count; i++) {
if (!s->files[i].marked) continue;
total++;
if (s->files[i].is_dir) ndirs++;
else if (s->files[i].is_link) nlinks++;
else nfiles++;
char fp[MAX_PATH]; join_path(fp, s->current_path, s->files[i].name);
total_size += s->files[i].is_dir ? calc_dir_size(fp) : s->files[i].size;
}
}
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_ItemsSelected"),
total, total == 1 ? "" : "s");
if (ndirs > 0 && nfiles > 0)
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_FilesDirs"), nfiles, ndirs);
else if (ndirs > 0)
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Dirs"), ndirs);
else
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Files"), nfiles);
if (nlinks > 0)
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_Symlinks"), nlinks);
char sz[32];
format_size(total_size, sz);
snprintf(fileinfo_lines[fileinfo_line_count++], 256, tr("FileInfo_TotalSize"), sz);
fileinfo_is_multi = true;
fileinfo_is_dir = (ndirs > 0 && nfiles == 0 && nlinks == 0);
fileinfo_active = true;
}
// ---------------------------------------------------------------------------
// Settings page — tabbed layout
// ---------------------------------------------------------------------------
typedef enum { STYPE_PRESET, STYPE_FONT, STYPE_INT, STYPE_ACTION,
STYPE_BOOL, STYPE_KEYBIND, STYPE_PATH, STYPE_CYCLE, STYPE_LANG } SettingType;
typedef struct {
const char *label;
SettingType type;
int *int_ptr;
bool *bool_ptr;
SDL_GameControllerButton *btn_ptr;
char *str_ptr;
int step, lo, hi;
const char **opts; // STYPE_CYCLE: option label array; hi = count
} SettingDef;
#define SETTINGS_TAB_COUNT 3
static const char *settings_tab_labels[SETTINGS_TAB_COUNT] = { "Settings_TabGeneral", "Settings_TabDisplay", "Settings_TabKeys" };
static int settings_tab = 0;
static int settings_tab_indices[SETTINGS_TAB_COUNT] = { 0, 0, 0 };
static const char *rotation_opts[] = { "Settings_RotNone", "Settings_Rot90", "Settings_Rot180", "Settings_Rot270" };
static SettingDef general_defs[] = {
{ "Settings_Language", STYPE_LANG, NULL, NULL, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_ShowHidden", STYPE_BOOL, NULL, &cfg.show_hidden, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_RememberDirs", STYPE_BOOL, NULL, &cfg.remember_dirs, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_SinglePane", STYPE_BOOL, NULL, &cfg.single_pane, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_PasteToOpposite", STYPE_BOOL, NULL, &cfg.paste_to_opposite, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_TwoMenuMode", STYPE_BOOL, NULL, &cfg.two_menu_mode, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_StartLeft", STYPE_PATH, NULL, NULL, NULL, cfg.start_left, 0, 0, 0, NULL },
{ "Settings_StartRight", STYPE_PATH, NULL, NULL, NULL, cfg.start_right, 0, 0, 0, NULL },
{ "Settings_ExecScripts", STYPE_BOOL, NULL, &cfg.exec_scripts, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_UISounds", STYPE_BOOL, NULL, &cfg.ui_sounds, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_SaveConfig", STYPE_ACTION,NULL, NULL, NULL, NULL, 0, 0, 0, NULL },
{ "Settings_Close", STYPE_ACTION,NULL, NULL, NULL, NULL, 0, 0, 0, NULL },
};
static SettingDef display_defs[] = {
{ "Settings_Rotation", STYPE_CYCLE, &cfg.rotation, NULL, NULL, NULL, 0, 0, 4, rotation_opts },
{ "Settings_ScreenWidth", STYPE_INT, &cfg.screen_w, NULL, NULL, NULL, 16, 320, 1920 },
{ "Settings_ScreenHeight", STYPE_INT, &cfg.screen_h, NULL, NULL, NULL, 16, 240, 1080 },
{ "Settings_ThemePreset", STYPE_PRESET, NULL, NULL, NULL, NULL, 0, 0, 0 },
{ "Settings_TintIcons", STYPE_BOOL, NULL, &cfg.tint_icons, NULL, NULL, 0, 0, 0 },
{ "Settings_FontFile", STYPE_FONT, NULL, NULL, NULL, NULL, 0, 0, 0 },
{ "Settings_FontList", STYPE_INT, &cfg.font_size_list, NULL, NULL, NULL, 1, 8, 48 },
{ "Settings_FontHeader", STYPE_INT, &cfg.font_size_header, NULL, NULL, NULL, 1, 8, 48 },
{ "Settings_FontFooter", STYPE_INT, &cfg.font_size_footer, NULL, NULL, NULL, 1, 8, 48 },
{ "Settings_FontMenu", STYPE_INT, &cfg.font_size_menu, NULL, NULL, NULL, 1, 8, 48 },
{ "Settings_SaveConfig", STYPE_ACTION, NULL, NULL, NULL, NULL, 0, 0, 0 },
{ "Settings_Close", STYPE_ACTION, NULL, NULL, NULL, NULL, 0, 0, 0 },
};
// Pending key bindings — edited in-session, only written to cfg on explicit Save.
// Prevents live rebinding from locking the user out of settings mid-session.
typedef struct {
SDL_GameControllerButton k_confirm, k_back, k_menu, k_mark;
SDL_GameControllerButton k_pgup, k_pgdn;
SDL_GameControllerButton k_menu2;
SDL_GameControllerButton osk_k_type, osk_k_bksp, osk_k_shift;
SDL_GameControllerButton osk_k_cancel, osk_k_toggle, osk_k_ins;
} PendingKeys;
static PendingKeys pending_keys;
// Per-group pointer arrays for duplicate detection.
// General and OSK keys are checked independently — cross-group sharing is fine
// (e.g. Confirm and OSK: Type Key can both be A).
static SDL_GameControllerButton *pending_general_ptrs[] = {
&pending_keys.k_confirm, &pending_keys.k_back,
&pending_keys.k_menu, &pending_keys.k_mark,
&pending_keys.k_pgup, &pending_keys.k_pgdn,
&pending_keys.k_menu2,
};
static SDL_GameControllerButton *pending_osk_ptrs[] = {
&pending_keys.osk_k_type, &pending_keys.osk_k_bksp,
&pending_keys.osk_k_shift, &pending_keys.osk_k_cancel,
&pending_keys.osk_k_toggle, &pending_keys.osk_k_ins,
};
#define PENDING_GENERAL_COUNT ((int)(sizeof(pending_general_ptrs)/sizeof(pending_general_ptrs[0])))
#define PENDING_OSK_COUNT ((int)(sizeof(pending_osk_ptrs)/sizeof(pending_osk_ptrs[0])))
// Returns the group array + count for a given btn_ptr, or NULL if not found.
static SDL_GameControllerButton **pending_group_for(SDL_GameControllerButton *target, int *count) {
for (int i = 0; i < PENDING_GENERAL_COUNT; i++)
if (pending_general_ptrs[i] == target) { *count = PENDING_GENERAL_COUNT; return pending_general_ptrs; }
for (int i = 0; i < PENDING_OSK_COUNT; i++)
if (pending_osk_ptrs[i] == target) { *count = PENDING_OSK_COUNT; return pending_osk_ptrs; }
*count = 0; return NULL;
}
static void pending_keys_from_cfg(void) {
pending_keys.k_confirm = cfg.k_confirm;
pending_keys.k_back = cfg.k_back;
pending_keys.k_menu = cfg.k_menu;
pending_keys.k_mark = cfg.k_mark;
pending_keys.k_pgup = cfg.k_pgup;
pending_keys.k_pgdn = cfg.k_pgdn;
pending_keys.k_menu2 = cfg.k_menu2;
pending_keys.osk_k_type = cfg.osk_k_type;
pending_keys.osk_k_bksp = cfg.osk_k_bksp;
pending_keys.osk_k_shift = cfg.osk_k_shift;
pending_keys.osk_k_cancel = cfg.osk_k_cancel;
pending_keys.osk_k_toggle = cfg.osk_k_toggle;
pending_keys.osk_k_ins = cfg.osk_k_ins;
}
static bool pending_keys_valid(void) {
if (pending_keys.k_confirm == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.k_back == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.k_menu == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.k_mark == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.k_pgup == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.k_pgdn == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (cfg.two_menu_mode && pending_keys.k_menu2 == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_type == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_bksp == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_shift == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_cancel == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_toggle == SDL_CONTROLLER_BUTTON_INVALID) return false;
if (pending_keys.osk_k_ins == SDL_CONTROLLER_BUTTON_INVALID) return false;
return true;
}
static void pending_keys_to_cfg(void) {
cfg.k_confirm = pending_keys.k_confirm;
cfg.k_back = pending_keys.k_back;
cfg.k_menu = pending_keys.k_menu;
cfg.k_mark = pending_keys.k_mark;
cfg.k_pgup = pending_keys.k_pgup;
cfg.k_pgdn = pending_keys.k_pgdn;
cfg.k_menu2 = pending_keys.k_menu2;
cfg.osk_k_type = pending_keys.osk_k_type;
cfg.osk_k_bksp = pending_keys.osk_k_bksp;
cfg.osk_k_shift = pending_keys.osk_k_shift;
cfg.osk_k_cancel = pending_keys.osk_k_cancel;
cfg.osk_k_toggle = pending_keys.osk_k_toggle;
cfg.osk_k_ins = pending_keys.osk_k_ins;
}
static SettingDef keys_defs[] = {
{ "Settings_KeyConfirm", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_confirm, NULL, 0, 0, 0 },
{ "Settings_KeyBack", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_back, NULL, 0, 0, 0 },
{ "Settings_KeyMenu", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_menu, NULL, 0, 0, 0 },
{ "Settings_KeyMenu2", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_menu2, NULL, 0, 0, 0 },
{ "Settings_KeyMark", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_mark, NULL, 0, 0, 0 },
{ "Settings_KeyPageUp", STYPE_KEYBIND, NULL, NULL, &pending_keys.k_pgup, NULL, 0, 0, 0 },
{ "Settings_KeyPageDown",STYPE_KEYBIND, NULL, NULL, &pending_keys.k_pgdn, NULL, 0, 0, 0 },
{ "Settings_OskType", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_type, NULL, 0, 0, 0 },
{ "Settings_OskBksp", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_bksp, NULL, 0, 0, 0 },
{ "Settings_OskShift", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_shift, NULL, 0, 0, 0 },
{ "Settings_OskCancel", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_cancel, NULL, 0, 0, 0 },
{ "Settings_OskToggle", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_toggle, NULL, 0, 0, 0 },
{ "Settings_OskInsOvr", STYPE_KEYBIND, NULL, NULL, &pending_keys.osk_k_ins, NULL, 0, 0, 0 },
{ "Settings_SaveConfig", STYPE_ACTION, NULL, NULL, NULL, NULL, 0, 0, 0 },
{ "Settings_Close", STYPE_ACTION, NULL, NULL, NULL, NULL, 0, 0, 0 },
};
static SettingDef *tab_defs(int *count) {
switch (settings_tab) {
case 0: *count = (int)(sizeof(general_defs)/sizeof(general_defs[0])); return general_defs;
case 1: *count = (int)(sizeof(display_defs)/sizeof(display_defs[0])); return display_defs;
case 2: *count = (int)(sizeof(keys_defs)/sizeof(keys_defs[0])); return keys_defs;
default: *count = 0; return NULL;
}
}
static bool settings_dirty = false; // unsaved changes pending
static bool settings_save_prompt = false; // "save before close?" modal active
static int save_prompt_sel = 0; // 0=Save, 1=Discard
static Uint32 settings_save_toast = 0; // non-zero until toast expires
static int settings_toast_tw = 0; // cached toast text width (set when toast activates)
static char settings_toast_msg[64] = "Config saved.";
static Uint32 explorer_toast_until = 0; // non-zero until toast expires
static int explorer_toast_tw = 0; // cached text width
static char explorer_toast_msg[64] = "";
static AppConfig cfg_snapshot; // cfg state at settings open (for discard)
static int snapshot_theme_idx = -1; // current_named_theme at settings open
static int snapshot_font_idx = 0; // current_font_idx at settings open
static int snapshot_lang_idx = 0; // current_lang_idx at settings open
static bool settings_listening = false; // waiting for next button press to bind
static SDL_GameControllerButton *settings_listen_target = NULL;
// ---------------------------------------------------------------------------
// Glyph cache
// ---------------------------------------------------------------------------
void destroy_glyph_cache() {
for (int i = 0; i < GLYPH_CACHE_SIZE; i++) {
if (glyph_cache[i].texture) { SDL_DestroyTexture(glyph_cache[i].texture); glyph_cache[i].texture = NULL; }
}
}
void draw_txt(TTF_Font *f, const char *txt, int x, int y, SDL_Color col) {
if (!txt || !txt[0]) return;
for (int i = 0; i < GLYPH_CACHE_SIZE; i++) {
GlyphEntry *e = &glyph_cache[i];
if (!e->texture) continue;
if (e->font == f && e->color.r == col.r && e->color.g == col.g &&
e->color.b == col.b && e->color.a == col.a &&
strncmp(e->text, txt, MAX_PATH - 1) == 0) {
e->last_used = glyph_frame;
SDL_Rect r = { x, y, e->w, e->h }; SDL_RenderCopy(renderer, e->texture, NULL, &r);
return;
}
}
SDL_Surface *surf = TTF_RenderUTF8_Blended(f, txt, col);
if (!surf) return;
SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, surf);
int slot = 0; Uint32 oldest = UINT32_MAX;
for (int i = 0; i < GLYPH_CACHE_SIZE; i++) {
if (!glyph_cache[i].texture) { slot = i; oldest = 0; break; }
if (glyph_cache[i].last_used < oldest) { oldest = glyph_cache[i].last_used; slot = i; }
}
if (glyph_cache[slot].texture) SDL_DestroyTexture(glyph_cache[slot].texture);
strncpy(glyph_cache[slot].text, txt, MAX_PATH - 1); glyph_cache[slot].text[MAX_PATH - 1] = '\0';
glyph_cache[slot].font = f; glyph_cache[slot].color = col; glyph_cache[slot].texture = tex;
glyph_cache[slot].w = surf->w; glyph_cache[slot].h = surf->h; glyph_cache[slot].last_used = glyph_frame;
SDL_Rect r = { x, y, surf->w, surf->h }; SDL_RenderCopy(renderer, tex, NULL, &r);
SDL_FreeSurface(surf);
}
// ---------------------------------------------------------------------------
// draw_txt_clipped — like draw_txt but truncates to max_w pixels with "…"
// ---------------------------------------------------------------------------
void draw_txt_clipped(TTF_Font *f, const char *txt, int x, int y, int max_w, SDL_Color col) {
if (!txt || !txt[0] || !f) return;
int w = 0;
TTF_SizeUTF8(f, txt, &w, NULL);
if (w <= max_w) { draw_txt(f, txt, x, y, col); return; }
// Walk bytes backwards to find a truncation point that fits with "…"
int ew = 0;
TTF_SizeUTF8(f, "\xe2\x80\xa6", &ew, NULL); // UTF-8 ellipsis U+2026
int avail = max_w - ew;
if (avail <= 0) return;
// Copy and shorten until it fits
char buf[MAX_LANG_VAL_LEN + 4];
strncpy(buf, txt, sizeof(buf) - 4); buf[sizeof(buf) - 4] = '\0';
int bl = (int)strlen(buf);
while (bl > 0) {
// Step back one UTF-8 codepoint
bl--;
while (bl > 0 && (buf[bl] & 0xC0) == 0x80) bl--;
buf[bl] = '\0';
TTF_SizeUTF8(f, buf, &w, NULL);
if (w <= avail) break;
}
// Append ellipsis
strcat(buf, "\xe2\x80\xa6");
draw_txt(f, buf, x, y, col);
}
// ---------------------------------------------------------------------------
// Font reload
// ---------------------------------------------------------------------------
static void reload_fonts() {
if (font_file_count == 0) return;
const char *fp = font_files[current_font_idx];
if (font_list) { TTF_CloseFont(font_list); font_list = TTF_OpenFont(fp, cfg.font_size_list); }
if (font_header) { TTF_CloseFont(font_header); font_header = TTF_OpenFont(fp, cfg.font_size_header); }
if (font_footer) { TTF_CloseFont(font_footer); font_footer = TTF_OpenFont(fp, cfg.font_size_footer); }
if (font_menu) { TTF_CloseFont(font_menu); font_menu = TTF_OpenFont(fp, cfg.font_size_menu); }
if (font_hex) { TTF_CloseFont(font_hex); font_hex = TTF_OpenFont(fp, cfg.font_size_hex); }
destroy_glyph_cache();
vtree_log("Fonts reloaded: %s list=%d header=%d footer=%d menu=%d hex=%d\n",
fp, cfg.font_size_list, cfg.font_size_header,
cfg.font_size_footer, cfg.font_size_menu, cfg.font_size_hex);
}
// Shorten a path to fit within max_w pixels. First strips leading components
// replacing each with "../"; if still too wide, sheds those prefixes too.
// Result written into out (size out_size). Falls back to bare filename.
static void shorten_path(const char *path, char *out, size_t out_size,
TTF_Font *font, int max_w) {
if (!font) { strncpy(out, path, out_size - 1); out[out_size - 1] = '\0'; return; }
// Try full path first
int pw = 0;
TTF_SizeUTF8(font, path, &pw, NULL);
if (pw <= max_w) { strncpy(out, path, out_size - 1); out[out_size - 1] = '\0'; return; }
// Walk forward stripping one component at a time from the left
const char *cur = path;
if (*cur == '/') cur++; // skip leading slash
int stripped = 0;
while (*cur) {
const char *slash = strchr(cur, '/');
if (!slash) break; // only one component left — can't strip further
stripped++;
cur = slash + 1;
// Build candidate: stripped × "../" + remaining
char candidate[MAX_PATH * 2];
int off = 0;
for (int i = 0; i < stripped && off < (int)sizeof(candidate) - 4; i++) {
candidate[off++] = '.'; candidate[off++] = '.'; candidate[off++] = '/';
}
strncpy(candidate + off, cur, sizeof(candidate) - (size_t)off - 1);
candidate[sizeof(candidate) - 1] = '\0';
TTF_SizeUTF8(font, candidate, &pw, NULL);
if (pw <= max_w) { strncpy(out, candidate, out_size - 1); out[out_size - 1] = '\0'; return; }
}
// Nothing fits with all ../ prefixes — shed them one at a time
for (int s = stripped; s >= 0; s--) {
char candidate[MAX_PATH * 2];
int off = 0;
for (int i = 0; i < s && off < (int)sizeof(candidate) - 4; i++) {
candidate[off++] = '.'; candidate[off++] = '.'; candidate[off++] = '/';
}
strncpy(candidate + off, cur, sizeof(candidate) - (size_t)off - 1);
candidate[sizeof(candidate) - 1] = '\0';
TTF_SizeUTF8(font, candidate, &pw, NULL);
if (pw <= max_w) { strncpy(out, candidate, out_size - 1); out[out_size - 1] = '\0'; return; }
}
// Even bare filename doesn't fit — return it anyway (caller clips)
strncpy(out, cur, out_size - 1); out[out_size - 1] = '\0';
}
// ---------------------------------------------------------------------------
// Settings helpers + render
// ---------------------------------------------------------------------------
static void settings_adjust(int dir) {
int n; SettingDef *defs = tab_defs(&n);
if (!defs || settings_index >= n) return;
SettingDef *d = &defs[settings_index];
if (d->type == STYPE_INT && d->int_ptr) {
int old = *d->int_ptr;
*d->int_ptr = SDL_clamp(*d->int_ptr + dir * d->step, d->lo, d->hi);
vtree_log("Setting '%s': %d -> %d\n", d->label, old, *d->int_ptr);
settings_dirty = true;
if (*d->int_ptr != old &&
(d->int_ptr == &cfg.font_size_list ||
d->int_ptr == &cfg.font_size_header ||
d->int_ptr == &cfg.font_size_footer ||
d->int_ptr == &cfg.font_size_menu))
reload_fonts();
} else if (d->type == STYPE_BOOL && d->bool_ptr) {
if (d->bool_ptr == &cfg.paste_to_opposite && cfg.single_pane) { /* greyed out — no-op */ }
else {
*d->bool_ptr = !(*d->bool_ptr);
vtree_log("Setting '%s': %s\n", d->label, *d->bool_ptr ? "true" : "false");
settings_dirty = true;
if (d->bool_ptr == &cfg.show_hidden) {
load_dir(0, panes[0].current_path);
load_dir(1, panes[1].current_path);
} else if (d->bool_ptr == &cfg.exec_scripts && cfg.exec_scripts) {
copy_str(settings_toast_msg, tr("Settings_ExecWarning"), sizeof(settings_toast_msg));
settings_save_toast = SDL_GetTicks() + 3500;
settings_toast_tw = 0;
if (font_menu) TTF_SizeText(font_menu, settings_toast_msg, &settings_toast_tw, NULL);
}
} /* end else (not greyed) */
} else if (d->type == STYPE_CYCLE && d->int_ptr && d->opts) {
int count = d->hi;
*d->int_ptr = ((*d->int_ptr) + dir + count) % count;
vtree_log("Setting '%s': %s\n", d->label, d->opts[*d->int_ptr]);
settings_dirty = true;
} else if (d->type == STYPE_LANG) {
if (lang_file_count < 1) return;
current_lang_idx = (current_lang_idx + dir + lang_file_count) % lang_file_count;
copy_str(cfg.language_name, lang_names[current_lang_idx], sizeof(cfg.language_name));
lang_reload();
destroy_glyph_cache();
settings_dirty = true;
} else if (d->type == STYPE_PRESET) {
int n = named_theme_count;
if (n < 1) return;
int next = (current_named_theme < 0)
? ((dir > 0) ? 0 : n - 1)
: (current_named_theme + dir + n) % n;
vtree_log("Theme: %s -> %s\n",
current_named_theme >= 0 ? named_themes[current_named_theme].name : "(none)",
named_themes[next].name);
apply_theme_preset(next); destroy_glyph_cache();
settings_dirty = true;
} else if (d->type == STYPE_FONT) {
if (font_file_count < 1) return;
current_font_idx = (current_font_idx + dir + font_file_count) % font_file_count;
const char *bn = strrchr(font_files[current_font_idx], '/');
bn = bn ? bn + 1 : font_files[current_font_idx];
vtree_log("Font file: %s -> %s\n", cfg.font_path, bn);
copy_str(cfg.font_path, bn, sizeof(cfg.font_path));
copy_str(vtree_font_path, font_files[current_font_idx], sizeof(vtree_font_path));
reload_fonts();
settings_dirty = true;
}
}
static void settings_do_close() {
if (settings_dirty) {
// Discard path: restore cfg and UI state to what they were when settings opened
cfg = cfg_snapshot;
current_named_theme = snapshot_theme_idx;
current_font_idx = snapshot_font_idx;
current_lang_idx = snapshot_lang_idx;
if (font_file_count > 0 && current_font_idx < font_file_count)
copy_str(vtree_font_path, font_files[current_font_idx], sizeof(vtree_font_path));
lang_reload();
destroy_glyph_cache();
}
reload_fonts();
// Recompute logical dims from physical and (possibly changed) rotation
cfg.screen_w = (cfg.rotation == 1 || cfg.rotation == 3) ? phys_h : phys_w;
cfg.screen_h = (cfg.rotation == 1 || cfg.rotation == 3) ? phys_w : phys_h;
// Recreate render target for the new rotation
if (render_target) { SDL_DestroyTexture(render_target); render_target = NULL; }
if (cfg.rotation != 0) {
render_target = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
cfg.screen_w, cfg.screen_h);
if (render_target) SDL_SetRenderTarget(renderer, render_target);
} else {
SDL_SetRenderTarget(renderer, NULL);
}
SDL_SetWindowSize(window, phys_w, phys_h);
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
settings_dirty = false;
settings_save_prompt = false;
settings_listening = false;
settings_listen_target = NULL;
current_mode = MODE_EXPLORER;
}
static void settings_confirm() {
int n; SettingDef *defs = tab_defs(&n);
if (!defs || settings_index >= n) return;
SettingDef *d = &defs[settings_index];
if (d->type == STYPE_ACTION) {
if (settings_index == n - 2) { // Save Config
if (!pending_keys_valid()) {
copy_str(settings_toast_msg, tr("Settings_UnsetKey"), sizeof(settings_toast_msg));
settings_save_toast = SDL_GetTicks() + 1800;
settings_toast_tw = 0;
if (font_menu) TTF_SizeText(font_menu, settings_toast_msg, &settings_toast_tw, NULL);
return;
}
pending_keys_to_cfg();
save_config();
cfg_snapshot = cfg;
snapshot_theme_idx = current_named_theme;
snapshot_font_idx = current_font_idx;
snapshot_lang_idx = current_lang_idx;
settings_dirty = false;
settings_save_toast = SDL_GetTicks() + 1800;
settings_toast_tw = 0;
copy_str(settings_toast_msg, tr("Settings_Saved"), sizeof(settings_toast_msg));
if (font_menu) TTF_SizeText(font_menu, settings_toast_msg, &settings_toast_tw, NULL);
} else if (settings_index == n - 1) { // Close
if (settings_dirty) { settings_save_prompt = true; save_prompt_sel = 0; }
else settings_do_close();
}
} else if (d->type == STYPE_BOOL && d->bool_ptr) {
settings_adjust(1); // toggle
} else if (d->type == STYPE_CYCLE || d->type == STYPE_LANG) {
settings_adjust(1); // cycle forward
} else if (d->type == STYPE_KEYBIND && d->btn_ptr && !cfg.keyboard_mode) {
settings_listening = true;
settings_listen_target = d->btn_ptr;
} else if (d->type == STYPE_PATH && d->str_ptr) {
if (!cfg.remember_dirs)
osk_enter_path(d->str_ptr, d->str_ptr);
}
}
static void settings_try_close() { // called from B/back button
if (settings_dirty) { settings_save_prompt = true; save_prompt_sel = 0; }
else settings_do_close();
}
static void draw_settings() {
SDL_SetRenderDrawColor(renderer, cfg.theme.bg.r, cfg.theme.bg.g, cfg.theme.bg.b, 255);
SDL_RenderClear(renderer);
int hh = cfg.font_size_header + 12;
int th = cfg.font_size_menu + 10; // tab strip height
int ih = cfg.font_size_list + 10;
int cl = 20;
int cv = cfg.screen_w / 2 + 20;
int aw = cfg.font_size_list;
int fh = cfg.font_size_footer + 16;
int rows_y0 = hh + th; // rows start below header + tab strip
// Header bar
SDL_SetRenderDrawColor(renderer, cfg.theme.header_bg.r, cfg.theme.header_bg.g, cfg.theme.header_bg.b, 255);
SDL_Rect hr = {0, 0, cfg.screen_w, hh}; SDL_RenderFillRect(renderer, &hr);
draw_txt(font_header, tr("Settings_Header"), cl, (hh - cfg.font_size_header) / 2, cfg.theme.text);
// Tab strip
int tab_w = cfg.screen_w / SETTINGS_TAB_COUNT;
for (int t = 0; t < SETTINGS_TAB_COUNT; t++) {
SDL_Rect tab_rect = {t * tab_w, hh, tab_w, th};
if (t == settings_tab) {
SDL_SetRenderDrawColor(renderer, cfg.theme.highlight_bg.r, cfg.theme.highlight_bg.g, cfg.theme.highlight_bg.b, 255);
} else {
SDL_SetRenderDrawColor(renderer, cfg.theme.alt_bg.r, cfg.theme.alt_bg.g, cfg.theme.alt_bg.b, 255);
}
SDL_RenderFillRect(renderer, &tab_rect);
SDL_Color tc = (t == settings_tab) ? cfg.theme.highlight_text : cfg.theme.text_disabled;
int tw_px = 0;
const char *tab_lbl = tr(settings_tab_labels[t]);
if (font_menu) TTF_SizeText(font_menu, tab_lbl, &tw_px, NULL);
int tx = t * tab_w + (tab_w - tw_px) / 2;
draw_txt_clipped(font_menu, tab_lbl, tx, hh + (th - cfg.font_size_menu) / 2, tab_w - 4, tc);
}
// Tab strip bottom border
SDL_SetRenderDrawColor(renderer, cfg.theme.text_disabled.r, cfg.theme.text_disabled.g, cfg.theme.text_disabled.b, 255);
SDL_RenderDrawLine(renderer, 0, hh + th - 1, cfg.screen_w, hh + th - 1);
// Settings rows — scrolled so the selected item is always visible
int n; SettingDef *defs = tab_defs(&n);
int max_rows = (cfg.screen_h - rows_y0 - fh) / ih;
if (max_rows < 1) max_rows = 1;