Repository navigation
Expand file tree
/
Copy pathBashMenuGenerator.cpp
More file actions
7021 lines (6513 loc) · 331 KB
/
Copy pathBashMenuGenerator.cpp
File metadata and controls
7021 lines (6513 loc) · 331 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
//Created with God, love and electricity, BMG 1.5.0 Release-Stable
// BashMenuGenerator - the Linux / POSIX edition of BatchMenuGenerator.
//
// Build: bash build.sh (stripped, fully static binary; see build.sh for the options)
// or: g++ -std=c++14 -O2 -o BashMenuGenerator BashMenuGenerator.cpp
// Run: ./BashMenuGenerator (interactive)
// ./BashMenuGenerator -h (command-line switches)
//
// Needs only a POSIX system and a terminal. Optional helpers that are used when present:
// zenity / kdialog / yad / qarma (graphical file browsers), xclip / xsel / wl-clipboard (clipboard),
// a C compiler (cc, gcc, clang, tcc) for "Compile to binary", sudo or doas inside root scripts.
#include <algorithm>
#include <cerrno>
#include <cctype>
#include <climits>
#include <csignal>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <dirent.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
// ============================================================
// UTF-8 helpers
// ============================================================
// Text is kept as UTF-8 std::string everywhere. Bytes that are not valid UTF-8 are carried through
// the editor as code points U+DC80..U+DCFF and written back as the original byte, so opening and
// saving a file never corrupts it.
static void AppendUtf8(std::string& out, char32_t cp) {
if (cp >= 0xDC80 && cp <= 0xDCFF) { out.push_back((char)(cp - 0xDC00)); return; }
if (cp < 0x80) {
out.push_back((char)cp);
} else if (cp < 0x800) {
out.push_back((char)(0xC0 | (cp >> 6)));
out.push_back((char)(0x80 | (cp & 0x3F)));
} else if (cp < 0x10000) {
out.push_back((char)(0xE0 | (cp >> 12)));
out.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out.push_back((char)(0x80 | (cp & 0x3F)));
} else {
out.push_back((char)(0xF0 | (cp >> 18)));
out.push_back((char)(0x80 | ((cp >> 12) & 0x3F)));
out.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out.push_back((char)(0x80 | (cp & 0x3F)));
}
}
static std::u32string Utf8ToU32(const std::string& s) {
std::u32string out;
out.reserve(s.size());
size_t i = 0;
const size_t n = s.size();
while (i < n) {
const unsigned char c = (unsigned char)s[i];
if (c < 0x80) { out.push_back(c); ++i; continue; }
size_t len = 0;
char32_t cp = 0;
if ((c & 0xE0) == 0xC0) { len = 2; cp = c & 0x1F; }
else if ((c & 0xF0) == 0xE0) { len = 3; cp = c & 0x0F; }
else if ((c & 0xF8) == 0xF0) { len = 4; cp = c & 0x07; }
bool ok = (len != 0 && i + len <= n);
if (ok) {
for (size_t k = 1; k < len; ++k) {
const unsigned char cc = (unsigned char)s[i + k];
if ((cc & 0xC0) != 0x80) { ok = false; break; }
cp = (cp << 6) | (cc & 0x3F);
}
}
if (ok) {
if ((len == 2 && cp < 0x80) || (len == 3 && cp < 0x800) || (len == 4 && cp < 0x10000) ||
cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) ok = false;
}
if (ok) { out.push_back(cp); i += len; }
else { out.push_back((char32_t)(0xDC00 + c)); ++i; }
}
return out;
}
static std::string U32ToUtf8(const std::u32string& s) {
std::string out;
out.reserve(s.size());
for (char32_t c : s) AppendUtf8(out, c);
return out;
}
// Columns a code point occupies in a terminal. Control characters are drawn as a one-column dot.
static int CharWidth(char32_t c) {
if (c == 0) return 0;
if (c < 0x20 || (c >= 0x7F && c < 0xA0)) return 1;
if (c >= 0xDC80 && c <= 0xDCFF) return 1;
if ((c >= 0x0300 && c <= 0x036F) || (c >= 0x1AB0 && c <= 0x1AFF) || (c >= 0x1DC0 && c <= 0x1DFF) ||
(c >= 0x20D0 && c <= 0x20FF) || (c >= 0xFE00 && c <= 0xFE0F) || (c >= 0xFE20 && c <= 0xFE2F) ||
c == 0x200B || c == 0x200C || c == 0x200D || c == 0xFEFF) return 0;
if ((c >= 0x1100 && c <= 0x115F) || (c >= 0x2E80 && c <= 0x303E) || (c >= 0x3041 && c <= 0x33FF) ||
(c >= 0x3400 && c <= 0x4DBF) || (c >= 0x4E00 && c <= 0x9FFF) || (c >= 0xA000 && c <= 0xA4CF) ||
(c >= 0xAC00 && c <= 0xD7A3) || (c >= 0xF900 && c <= 0xFAFF) || (c >= 0xFE30 && c <= 0xFE6F) ||
(c >= 0xFF00 && c <= 0xFF60) || (c >= 0xFFE0 && c <= 0xFFE6) || (c >= 0x1F300 && c <= 0x1F64F) ||
(c >= 0x1F900 && c <= 0x1F9FF) || (c >= 0x20000 && c <= 0x3FFFD)) return 2;
return 1;
}
// What is actually drawn for a code point (control characters and stray bytes become a dot).
static char32_t DisplayChar(char32_t c) {
if (c < 0x20 || (c >= 0x7F && c < 0xA0) || (c >= 0xDC80 && c <= 0xDCFF)) return 0x00B7;
return c;
}
static int DisplayWidth(const std::string& s) {
int w = 0;
for (char32_t c : Utf8ToU32(s)) w += CharWidth(c);
return w;
}
// First code point of a string as UTF-8 (empty string stays empty).
static std::string FirstChar(const std::string& s) {
std::u32string u = Utf8ToU32(s);
if (u.empty()) return "";
std::string out;
AppendUtf8(out, u[0]);
return out;
}
// Cuts a string so it fits in 'cols' terminal columns.
static std::string FitToWidth(const std::string& s, int cols) {
if (cols <= 0) return "";
std::string out;
int w = 0;
for (char32_t c : Utf8ToU32(s)) {
const char32_t shown = DisplayChar(c);
const int cw = CharWidth(shown);
if (w + cw > cols) break;
AppendUtf8(out, shown);
w += cw;
}
return out;
}
// ============================================================
// String helpers
// ============================================================
static std::string Trim(const std::string& str) {
size_t first = 0;
while (first < str.size() && (unsigned char)str[first] <= 32) ++first;
if (first == str.size()) return "";
size_t last = str.size() - 1;
while (last > first && (unsigned char)str[last] <= 32) --last;
return str.substr(first, last - first + 1);
}
static bool StartsWith(const std::string& s, const std::string& prefix) {
return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}
static bool EndsWith(const std::string& s, const std::string& suffix) {
return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
static std::string ToLower(std::string s) {
for (auto& ch : s) ch = (char)std::tolower((unsigned char)ch);
return s;
}
static bool EndsWithNoCase(const std::string& s, const std::string& suffix) {
return EndsWith(ToLower(s), ToLower(suffix));
}
static bool IsYes(const std::string& raw) {
const std::string v = ToLower(Trim(raw));
return v == "y" || v == "yes" || v == "true" || v == "on" || v == "1";
}
static std::string ReplaceAll(std::string s, const std::string& from, const std::string& to) {
if (from.empty()) return s;
size_t pos = 0;
while ((pos = s.find(from, pos)) != std::string::npos) {
s.replace(pos, from.size(), to);
pos += to.size();
}
return s;
}
static std::vector<std::string> SplitLines(const std::string& text) {
std::vector<std::string> lines;
size_t start = 0;
for (size_t i = 0; i < text.size(); ++i) {
if (text[i] != '\r' && text[i] != '\n') continue;
lines.push_back(text.substr(start, i - start));
if (text[i] == '\r' && i + 1 < text.size() && text[i + 1] == '\n') ++i;
start = i + 1;
}
if (start < text.size()) lines.push_back(text.substr(start));
else if (!text.empty() && (text.back() == '\r' || text.back() == '\n')) lines.push_back("");
return lines;
}
// Wraps a string in single quotes for sh/bash. A single quote inside becomes '\''.
static std::string ShQuote(const std::string& s) {
std::string r = "'";
for (char ch : s) {
if (ch == '\'') r += "'\\''";
else r += ch;
}
r += "'";
return r;
}
// Inverse of ShQuote for one quoted word starting at 'pos' (which must point at the opening quote).
// Understands the '\'' idiom. On success 'pos' is moved just past the quoted word.
static bool ShUnquoteAt(const std::string& s, size_t& pos, std::string& out) {
out.clear();
size_t i = pos;
bool any = false;
while (i < s.size()) {
if (s[i] == '\'') {
size_t close = s.find('\'', i + 1);
if (close == std::string::npos) return false;
out.append(s, i + 1, close - i - 1);
i = close + 1;
any = true;
} else if (s.compare(i, 2, "\\'") == 0 && any) {
out += '\'';
i += 2;
} else {
break;
}
}
if (!any) return false;
pos = i;
return true;
}
static std::string ToStr(long long v) { return std::to_string(v); }
static std::string HexOf(const unsigned char* data, size_t len) {
static const char* d = "0123456789abcdef";
std::string r;
r.reserve(len * 2);
for (size_t i = 0; i < len; ++i) { r += d[data[i] >> 4]; r += d[data[i] & 15]; }
return r;
}
// ============================================================
// File, path and environment helpers
// ============================================================
static bool PathExists(const std::string& path) {
struct stat st;
return !path.empty() && stat(path.c_str(), &st) == 0;
}
static bool DirExists(const std::string& path) {
struct stat st;
return !path.empty() && stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
static bool IsRegularFile(const std::string& path) {
struct stat st;
return !path.empty() && stat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode);
}
static bool IsSymlink(const std::string& path) {
struct stat st;
return !path.empty() && lstat(path.c_str(), &st) == 0 && S_ISLNK(st.st_mode);
}
static std::string GetEnv(const char* name) {
const char* v = getenv(name);
return v ? std::string(v) : std::string();
}
// The current user's home folder from /etc/passwd. Read by hand instead of calling getpwuid() so that a
// statically linked build does not depend on the C library's name-service plug-ins at run time.
static std::string HomeFromPasswdFile() {
FILE* f = fopen("/etc/passwd", "r");
if (!f) return "";
const std::string uid = std::to_string((long long)getuid());
std::string home;
char buf[2048];
while (home.empty() && fgets(buf, sizeof(buf), f)) {
std::string line = buf; // name:password:uid:gid:gecos:home:shell
while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back();
std::vector<std::string> field;
size_t start = 0;
for (size_t i = 0; i <= line.size(); ++i) {
if (i == line.size() || line[i] == ':') { field.push_back(line.substr(start, i - start)); start = i + 1; }
}
if (field.size() >= 6 && field[2] == uid && !field[5].empty() && field[5][0] == '/') home = field[5];
}
fclose(f);
return home;
}
static std::string HomeDir() {
std::string h = GetEnv("HOME");
if (!h.empty()) return h;
h = HomeFromPasswdFile();
return h.empty() ? "/tmp" : h;
}
static std::string CurrentDir() {
char buf[PATH_MAX];
if (getcwd(buf, sizeof(buf))) return buf;
return ".";
}
static std::string EnsureTrailingSlash(std::string p) {
if (p.empty() || p.back() != '/') p += '/';
return p;
}
static std::string TrimTrailingSlashes(std::string p) {
while (p.size() > 1 && p.back() == '/') p.pop_back();
return p;
}
static std::string DirName(const std::string& path) {
const std::string p = TrimTrailingSlashes(path);
size_t pos = p.find_last_of('/');
if (pos == std::string::npos) return ".";
if (pos == 0) return "/";
return p.substr(0, pos);
}
static std::string BaseName(const std::string& path) {
const std::string p = TrimTrailingSlashes(path);
size_t pos = p.find_last_of('/');
return pos == std::string::npos ? p : p.substr(pos + 1);
}
// File name without its last extension ("menu.sh" -> "menu").
static std::string BaseNameNoExt(const std::string& path) {
std::string b = BaseName(path);
size_t dot = b.find_last_of('.');
if (dot == std::string::npos || dot == 0) return b;
return b.substr(0, dot);
}
static std::string JoinPath(const std::string& a, const std::string& b) {
if (a.empty()) return b;
if (b.empty()) return a;
if (!b.empty() && b[0] == '/') return b;
return EnsureTrailingSlash(a) + b;
}
// ~ and ~/x expansion, as typed at a prompt.
static std::string ExpandTilde(const std::string& p) {
if (p == "~") return HomeDir();
if (StartsWith(p, "~/")) return HomeDir() + p.substr(1);
return p;
}
static std::string AbsolutePath(const std::string& p) {
if (p.empty()) return p;
std::string e = ExpandTilde(p);
char buf[PATH_MAX];
if (realpath(e.c_str(), buf)) return buf;
if (e[0] == '/') return e;
return JoinPath(CurrentDir(), e);
}
// Strips one pair of surrounding quotes (a path pasted from a file manager is often quoted).
static std::string StripQuotes(std::string s) {
s = Trim(s);
if (s.size() >= 2 && ((s.front() == '"' && s.back() == '"') || (s.front() == '\'' && s.back() == '\'')))
s = s.substr(1, s.size() - 2);
return s;
}
// mkdir -p. Returns true when the directory exists afterwards.
static bool EnsureDirectoryTree(const std::string& directory, mode_t mode = 0755) {
std::string d = TrimTrailingSlashes(directory);
if (d.empty()) return false;
if (DirExists(d)) return true;
for (size_t pos = 1; pos < d.size(); ++pos) {
if (d[pos] != '/') continue;
const std::string partial = d.substr(0, pos);
if (!DirExists(partial)) mkdir(partial.c_str(), mode);
}
mkdir(d.c_str(), mode);
return DirExists(d);
}
static bool ReadBinaryFile(const std::string& path, std::string& data) {
data.clear();
FILE* f = fopen(path.c_str(), "rb");
if (!f) return false;
char buf[65536];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) data.append(buf, n);
const bool ok = !ferror(f);
fclose(f);
return ok;
}
static bool WriteBinaryFile(const std::string& path, const std::string& data, mode_t mode = 0644) {
const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, mode);
if (fd < 0) return false;
size_t off = 0;
while (off < data.size()) {
const ssize_t n = write(fd, data.data() + off, data.size() - off);
if (n < 0) {
if (errno == EINTR) continue;
close(fd);
return false;
}
off += (size_t)n;
}
fchmod(fd, mode);
return close(fd) == 0;
}
static std::string GetExecutablePath() {
char buf[PATH_MAX];
const ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n > 0) { buf[n] = '\0'; return buf; }
return "";
}
static std::string GetExecutableDirectory() {
const std::string exe = GetExecutablePath();
return exe.empty() ? CurrentDir() : DirName(exe);
}
// Looks a program up on PATH. Returns its full path, or "" when it is not installed.
static std::string FindInPath(const std::string& name) {
if (name.empty()) return "";
if (name.find('/') != std::string::npos) {
return (access(name.c_str(), X_OK) == 0 && IsRegularFile(name)) ? name : "";
}
std::string path = GetEnv("PATH");
if (path.empty()) path = "/usr/local/bin:/usr/bin:/bin";
size_t start = 0;
while (start <= path.size()) {
size_t end = path.find(':', start);
if (end == std::string::npos) end = path.size();
std::string dir = path.substr(start, end - start);
if (dir.empty()) dir = ".";
const std::string candidate = JoinPath(dir, name);
if (IsRegularFile(candidate) && access(candidate.c_str(), X_OK) == 0) return candidate;
start = end + 1;
}
return "";
}
static bool CommandExists(const std::string& name) { return !FindInPath(name).empty(); }
static std::string MakeTempDir(const std::string& prefix) {
std::string base = GetEnv("TMPDIR");
if (base.empty() || !DirExists(base)) base = "/tmp";
std::string pattern = EnsureTrailingSlash(base) + prefix + "XXXXXX";
std::vector<char> buf(pattern.begin(), pattern.end());
buf.push_back('\0');
if (!mkdtemp(buf.data())) return "";
return std::string(buf.data());
}
static void RemoveTree(const std::string& path) {
if (path.empty() || path == "/") return;
DIR* d = opendir(path.c_str());
if (!d) { unlink(path.c_str()); return; }
struct dirent* e;
std::vector<std::string> names;
while ((e = readdir(d)) != nullptr) {
const std::string n = e->d_name;
if (n != "." && n != "..") names.push_back(n);
}
closedir(d);
for (const auto& n : names) {
const std::string child = path + "/" + n;
struct stat st;
if (lstat(child.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) RemoveTree(child);
else unlink(child.c_str());
}
rmdir(path.c_str());
}
static std::string TimestampNow(const char* format) {
char buf[128];
time_t t = time(nullptr);
struct tm tmv;
localtime_r(&t, &tmv);
strftime(buf, sizeof(buf), format, &tmv);
return buf;
}
static std::string RandomHex(size_t bytes) {
std::vector<unsigned char> raw(bytes, 0);
FILE* f = fopen("/dev/urandom", "rb");
bool ok = false;
if (f) { ok = fread(raw.data(), 1, bytes, f) == bytes; fclose(f); }
if (!ok) {
unsigned long long seed = (unsigned long long)time(nullptr) ^ ((unsigned long long)getpid() << 20) ^
(unsigned long long)clock();
for (size_t i = 0; i < bytes; ++i) {
seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
raw[i] = (unsigned char)(seed & 0xFF);
}
}
return HexOf(raw.data(), raw.size());
}
// ============================================================
// Running other programs
// ============================================================
struct ProcOpts {
std::string* out = nullptr; // capture stdout here
const std::string* in = nullptr; // feed this to stdin
bool quietErr = false; // send stderr to /dev/null
bool quietOut = false; // send stdout to /dev/null (ignored when 'out' is set)
bool detachedStdin = false; // stdin from /dev/null
const std::string* cwd = nullptr; // run in this directory
};
// Runs argv[0] (looked up on PATH). Returns the exit status, 128+signal when killed, or 127 when the
// program could not be started. While it runs, Ctrl+C is left to the child.
static int RunCommand(const std::vector<std::string>& argv, const ProcOpts& o = ProcOpts()) {
if (argv.empty()) return 127;
fflush(stdout);
fflush(stderr);
int outPipe[2] = { -1, -1 };
int inPipe[2] = { -1, -1 };
if (o.out && pipe(outPipe) != 0) return 127;
if (o.in && pipe(inPipe) != 0) {
if (outPipe[0] >= 0) { close(outPipe[0]); close(outPipe[1]); }
return 127;
}
struct sigaction ignore, oldInt, oldQuit;
memset(&ignore, 0, sizeof(ignore));
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
sigaction(SIGINT, &ignore, &oldInt);
sigaction(SIGQUIT, &ignore, &oldQuit);
const pid_t pid = fork();
if (pid < 0) {
sigaction(SIGINT, &oldInt, nullptr);
sigaction(SIGQUIT, &oldQuit, nullptr);
for (int fd : { outPipe[0], outPipe[1], inPipe[0], inPipe[1] }) if (fd >= 0) close(fd);
return 127;
}
if (pid == 0) {
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
if (o.cwd && !o.cwd->empty() && chdir(o.cwd->c_str()) != 0) _exit(127);
if (o.out) { dup2(outPipe[1], 1); close(outPipe[0]); close(outPipe[1]); }
else if (o.quietOut) { int n = open("/dev/null", O_WRONLY); if (n >= 0) { dup2(n, 1); close(n); } }
if (o.in) { dup2(inPipe[0], 0); close(inPipe[0]); close(inPipe[1]); }
else if (o.detachedStdin) { int n = open("/dev/null", O_RDONLY); if (n >= 0) { dup2(n, 0); close(n); } }
if (o.quietErr) { int n = open("/dev/null", O_WRONLY); if (n >= 0) { dup2(n, 2); close(n); } }
std::vector<char*> args;
for (const auto& a : argv) args.push_back(const_cast<char*>(a.c_str()));
args.push_back(nullptr);
execvp(args[0], args.data());
_exit(127);
}
if (outPipe[1] >= 0) close(outPipe[1]);
if (inPipe[0] >= 0) close(inPipe[0]);
signal(SIGPIPE, SIG_IGN);
size_t written = 0;
bool inOpen = o.in != nullptr;
bool outOpen = o.out != nullptr;
if (o.out) o.out->clear();
while (inOpen || outOpen) {
struct pollfd fds[2];
int n = 0;
int inIdx = -1, outIdx = -1;
if (inOpen) { fds[n].fd = inPipe[1]; fds[n].events = POLLOUT; fds[n].revents = 0; inIdx = n++; }
if (outOpen) { fds[n].fd = outPipe[0]; fds[n].events = POLLIN; fds[n].revents = 0; outIdx = n++; }
const int pr = poll(fds, (nfds_t)n, -1);
if (pr < 0) { if (errno == EINTR) continue; break; }
if (inIdx >= 0 && (fds[inIdx].revents & (POLLOUT | POLLERR | POLLHUP))) {
if (written >= o.in->size()) { close(inPipe[1]); inOpen = false; }
else {
const ssize_t w = write(inPipe[1], o.in->data() + written, o.in->size() - written);
if (w < 0) { if (errno != EINTR && errno != EAGAIN) { close(inPipe[1]); inOpen = false; } }
else written += (size_t)w;
if (inOpen && written >= o.in->size()) { close(inPipe[1]); inOpen = false; }
}
}
if (outIdx >= 0 && (fds[outIdx].revents & (POLLIN | POLLERR | POLLHUP))) {
char buf[4096];
const ssize_t r = read(outPipe[0], buf, sizeof(buf));
if (r > 0) o.out->append(buf, (size_t)r);
else if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN)) { close(outPipe[0]); outOpen = false; }
}
}
if (inOpen) close(inPipe[1]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
sigaction(SIGINT, &oldInt, nullptr);
sigaction(SIGQUIT, &oldQuit, nullptr);
if (WIFEXITED(status)) return WEXITSTATUS(status);
if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);
return 127;
}
static std::string FirstLine(const std::string& s) {
size_t e = s.find_first_of("\r\n");
return e == std::string::npos ? s : s.substr(0, e);
}
// ============================================================
// Terminal layer (raw mode, escape sequences, signals)
// ============================================================
static bool g_stdoutTty = false;
static bool g_stdinTty = false;
static bool g_ansi = false; // a real terminal that understands escape sequences (not piped, not TERM=dumb)
static bool g_color = true;
static bool g_enableTUI = true;
static bool g_enableSound = false;
static int g_col = 0; // best-effort cursor column of stdout
static volatile sig_atomic_t g_resizePending = 0;
static volatile sig_atomic_t g_altScreen = 0;
static volatile sig_atomic_t g_cursorHidden = 0;
static volatile sig_atomic_t g_pasteMode = 0;
static volatile sig_atomic_t g_titlePushed = 0;
static struct termios g_cookedTermios;
static bool g_haveCooked = false;
static volatile sig_atomic_t g_rawDepth = 0;
static void WriteRaw(const char* s) {
// async-signal-safe on purpose: used from signal handlers and atexit
const size_t n = strlen(s);
size_t off = 0;
while (off < n) {
const ssize_t w = write(1, s + off, n - off);
if (w <= 0) break;
off += (size_t)w;
}
}
static int TermCols() {
struct winsize ws;
if (ioctl(1, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return ws.ws_col;
if (ioctl(0, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return ws.ws_col;
const int env = atoi(GetEnv("COLUMNS").c_str());
return env > 0 ? env : 80;
}
static int TermRows() {
struct winsize ws;
if (ioctl(1, TIOCGWINSZ, &ws) == 0 && ws.ws_row > 0) return ws.ws_row;
if (ioctl(0, TIOCGWINSZ, &ws) == 0 && ws.ws_row > 0) return ws.ws_row;
const int env = atoi(GetEnv("LINES").c_str());
return env > 0 ? env : 24;
}
static void TermResetAll() {
if (g_ansi) {
if (g_pasteMode) { WriteRaw("\033[?2004l"); g_pasteMode = 0; }
if (g_altScreen) { WriteRaw("\033[?1049l"); g_altScreen = 0; }
if (g_cursorHidden) { WriteRaw("\033[?25h"); g_cursorHidden = 0; }
if (g_titlePushed) { WriteRaw("\033[23;0t"); g_titlePushed = 0; }
WriteRaw("\033[0m");
}
if (g_haveCooked && g_rawDepth > 0) {
tcsetattr(0, TCSANOW, &g_cookedTermios);
}
g_rawDepth = 0;
}
static void Flush() { fflush(stdout); }
[[noreturn]] static void Quit(int code) {
fflush(stdout);
TermResetAll();
exit(code);
}
static void OnFatalSignal(int sig) {
TermResetAll();
signal(sig, SIG_DFL);
raise(sig);
}
static void OnWinch(int) { g_resizePending = 1; }
static void InstallTerminalHandlers() {
g_stdoutTty = isatty(1) != 0;
g_stdinTty = isatty(0) != 0;
const std::string term = GetEnv("TERM");
g_ansi = g_stdoutTty && !term.empty() && term != "dumb";
g_color = g_ansi && GetEnv("NO_COLOR").empty();
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = OnFatalSignal;
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGHUP, &sa, nullptr);
sigaction(SIGQUIT, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
sa.sa_handler = OnWinch;
sigaction(SIGWINCH, &sa, nullptr); // no SA_RESTART: a resize interrupts a blocking read
signal(SIGPIPE, SIG_IGN);
atexit(TermResetAll);
}
static void EnterRaw() {
if (!g_stdinTty) return;
if (g_rawDepth++ > 0) return;
if (!g_haveCooked) {
if (tcgetattr(0, &g_cookedTermios) != 0) { g_rawDepth = 0; return; }
g_haveCooked = true;
}
struct termios t = g_cookedTermios;
t.c_iflag &= ~(tcflag_t)(BRKINT | ICRNL | INPCK | ISTRIP | IXON | INLCR | IGNCR);
t.c_lflag &= ~(tcflag_t)(ECHO | ICANON | IEXTEN | ISIG);
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &t);
}
static void LeaveRaw() {
if (g_rawDepth <= 0) return;
if (--g_rawDepth > 0) return;
if (g_haveCooked) tcsetattr(0, TCSANOW, &g_cookedTermios);
}
struct RawScope {
RawScope() { EnterRaw(); }
~RawScope() { LeaveRaw(); }
};
struct CursorScope {
bool changed;
explicit CursorScope(bool hide) : changed(false) {
if (hide && g_stdoutTty && !g_cursorHidden) { WriteRaw("\033[?25l"); g_cursorHidden = 1; changed = true; }
}
~CursorScope() {
if (changed && g_stdoutTty) { WriteRaw("\033[?25h"); g_cursorHidden = 0; }
}
};
struct PasteScope {
bool changed;
PasteScope() : changed(false) {
if (g_stdoutTty && g_stdinTty && !g_pasteMode) { WriteRaw("\033[?2004h"); g_pasteMode = 1; changed = true; }
}
~PasteScope() {
if (changed && g_stdoutTty) { WriteRaw("\033[?2004l"); g_pasteMode = 0; }
}
};
struct AltScreenScope {
bool changed;
AltScreenScope() : changed(false) {
if (g_stdoutTty && !g_altScreen) { WriteRaw("\033[?1049h\033[H\033[2J"); g_altScreen = 1; changed = true; }
}
~AltScreenScope() {
if (changed && g_stdoutTty) { WriteRaw("\033[?1049l"); g_altScreen = 0; }
}
};
// ============================================================
// Output (tracks the cursor column so the line editor knows where its prompt ended)
// ============================================================
static void Out(const std::string& s) {
if (s.empty()) return;
fwrite(s.data(), 1, s.size(), stdout);
size_t i = 0;
while (i < s.size()) {
const unsigned char c = (unsigned char)s[i];
if (c == 0x1B) {
size_t j = i + 1;
if (j < s.size() && s[j] == '[') {
++j;
while (j < s.size() && !((unsigned char)s[j] >= 0x40 && (unsigned char)s[j] <= 0x7E)) ++j;
++j;
} else if (j < s.size() && s[j] == ']') {
while (j < s.size() && s[j] != '\007') ++j;
++j;
} else {
++j;
}
i = j;
continue;
}
if (c == '\n' || c == '\r') { g_col = 0; ++i; continue; }
if (c == '\t') { g_col = (g_col / 8 + 1) * 8; ++i; continue; }
if (c < 0x20) { ++i; continue; }
size_t len = 1;
if ((c & 0xE0) == 0xC0) len = 2;
else if ((c & 0xF0) == 0xE0) len = 3;
else if ((c & 0xF8) == 0xF0) len = 4;
if (i + len > s.size()) len = s.size() - i;
const std::u32string u = Utf8ToU32(s.substr(i, len));
if (!u.empty()) g_col += CharWidth(u[0]);
i += len;
}
const int w = TermCols();
if (w > 0 && g_col >= w) g_col %= w;
}
static void Printf(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
static void Printf(const char* fmt, ...) {
char stackBuf[1024];
va_list ap, ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
const int n = vsnprintf(stackBuf, sizeof(stackBuf), fmt, ap);
va_end(ap);
if (n >= 0) {
if ((size_t)n < sizeof(stackBuf)) {
Out(std::string(stackBuf, (size_t)n));
} else {
std::string big((size_t)n + 1, '\0');
vsnprintf(&big[0], big.size(), fmt, ap2);
big.resize((size_t)n);
Out(big);
}
}
va_end(ap2);
}
static void ClearScreen() {
if (g_ansi) Out("\033[H\033[2J");
else Out("\n");
g_col = 0;
}
static void SetTerminalTitle(const std::string& title) {
if (!g_ansi) return;
if (!g_titlePushed) { Out("\033[22;0t"); g_titlePushed = 1; } // remember the old title, restored on exit
Out("\033]0;" + title + "\007");
}
// ============================================================
// Theme & Color Configuration
// ============================================================
// Colors use the same 0-15 numbers as the Windows edition (bit 0 blue, bit 1 green, bit 2 red,
// bit 3 bright). They are translated to ANSI at draw time. 15 (bright white) is drawn as bold in the
// terminal's own foreground color and 7 (light gray) as "reset", so light and dark terminals both work.
enum ConsoleColor {
CC_DEFAULT = -1,
CC_BLACK = 0,
CC_RESET = 7,
CC_CYAN = 11,
CC_YELLOW = 14,
CC_GREEN = 10,
CC_RED = 12,
CC_WHITE = 15,
CC_MAGENTA = 13,
CC_DARK_GREEN = 2,
CC_DARK_RED = 4,
CC_DARK_YELLOW = 6,
CC_DARK_WHITE = 8,
CC_BRIGHT_GREEN = 10,
CC_BRIGHT_CYAN = 11,
CC_BRIGHT_RED = 12,
CC_BRIGHT_WHITE = 15,
CC_VIOLET = 13,
CC_DARK_VIOLET = 5,
CC_GRAY = 8,
CC_LIGHT_GRAY = 7,
CC_BLUE = 9,
CC_DARK_BLUE = 1
};
struct Theme {
int header;
int prompt;
int input;
int success;
int error;
int info;
int banner;
int text;
int accent;
};
static const Theme kDefaultTheme = { CC_CYAN, CC_YELLOW, CC_WHITE, CC_GREEN, CC_RED, CC_MAGENTA, CC_CYAN, CC_DEFAULT, CC_YELLOW };
static Theme g_theme = kDefaultTheme;
static int AnsiIndex(int w) { return ((w & 1) << 2) | (w & 2) | ((w & 4) >> 2); }
static std::string ColorEsc(int color) {
if (!g_color) return "";
if (color == CC_RESET) return "\033[0m";
if (color < 0) return "\033[0m";
if (color == CC_WHITE) return "\033[0;1m";
const int base = (color & 8) ? 90 : 30;
return "\033[0;" + ToStr(base + AnsiIndex(color & 7)) + "m";
}
static std::string InvertedEsc(int bg, int fg) {
if (!g_color) return "\033[0;7m";
if (bg < 0) return "\033[0;7m";
const int bgBase = (bg & 8) ? 100 : 40;
const int fgBase = (fg & 8) ? 90 : 30;
return "\033[0;" + ToStr(fgBase + AnsiIndex(fg & 7)) + ";" + ToStr(bgBase + AnsiIndex(bg & 7)) + "m";
}
static void SetColor(int color) { Out(ColorEsc(color)); }
static void ApplyTheme(const std::string& themeName) {
if (themeName == "matrix") {
g_theme = { CC_DARK_GREEN, CC_GREEN, CC_BRIGHT_GREEN, CC_GREEN, CC_DARK_GREEN, CC_GREEN, CC_DARK_GREEN, CC_GREEN, CC_BRIGHT_GREEN };
} else if (themeName == "cyberpunk") {
g_theme = { CC_CYAN, CC_YELLOW, CC_MAGENTA, CC_GREEN, CC_RED, CC_MAGENTA, CC_CYAN, CC_DEFAULT, CC_YELLOW };
} else if (themeName == "cli") {
g_theme = { CC_LIGHT_GRAY, CC_GRAY, CC_BRIGHT_WHITE, CC_DEFAULT, CC_DARK_WHITE, CC_LIGHT_GRAY, CC_GRAY, CC_BRIGHT_WHITE, CC_DEFAULT };
} else if (themeName == "violent") {
g_theme = { CC_RED, CC_BRIGHT_RED, CC_MAGENTA, CC_GREEN, CC_DARK_RED, CC_VIOLET, CC_DARK_RED, CC_DEFAULT, CC_BRIGHT_RED };
} else {
g_theme = kDefaultTheme;
}
}
#define C_H SetColor(g_theme.header)
#define C_P SetColor(g_theme.prompt)
#define C_I SetColor(g_theme.input)
#define C_S SetColor(g_theme.success)
#define C_E SetColor(g_theme.error)
#define C_N SetColor(g_theme.info)
#define C_B SetColor(g_theme.banner)
#define C_T SetColor(g_theme.text)
#define C_A SetColor(g_theme.accent)
#define C_R SetColor(CC_RESET)
static void Sleep(int ms) {
Flush();
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (long)(ms % 1000) * 1000000L;
while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {}
}
// ============================================================
// Menu sounds
// ============================================================
// Order of preference: SoX "play" (exact tones, like the Windows beeps), the freedesktop sound theme
// through canberra-gtk-play or paplay, and finally the terminal bell.
static void SpawnDetached(const std::vector<std::string>& argv) {
if (argv.empty()) return;
const pid_t first = fork();
if (first < 0) return;
if (first == 0) {
const pid_t second = fork();
if (second != 0) _exit(0);
setsid();
const int n = open("/dev/null", O_RDWR);
if (n >= 0) { dup2(n, 0); dup2(n, 1); dup2(n, 2); if (n > 2) close(n); }
std::vector<char*> args;
for (const auto& a : argv) args.push_back(const_cast<char*>(a.c_str()));
args.push_back(nullptr);
execvp(args[0], args.data());
_exit(127);
}
int status = 0;
while (waitpid(first, &status, 0) < 0 && errno == EINTR) {}
}
static void PlayMenuSound(int type) {
if (!g_enableSound) return;
static int backend = -1; // 0 bell, 1 sox, 2 canberra, 3 paplay
static std::string themeDir = "/usr/share/sounds/freedesktop/stereo/";
if (backend < 0) {
if (CommandExists("play")) backend = 1;
else if (CommandExists("canberra-gtk-play")) backend = 2;
else if (CommandExists("paplay") && DirExists(themeDir)) backend = 3;
else backend = 0;
}
if (backend == 1) {
SpawnDetached({ "play", "-nq", "synth", type == 0 ? "0.02" : "0.045", "sine", type == 0 ? "750" : "1150" });
} else if (backend == 2) {
SpawnDetached({ "canberra-gtk-play", "-i", type == 0 ? "audio-volume-change" : "message" });
} else if (backend == 3) {
SpawnDetached({ "paplay", themeDir + (type == 0 ? "audio-volume-change.oga" : "message.oga") });
} else if (g_stdoutTty) {
WriteRaw("\a");
}
}