-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscpanel.cpp
More file actions
2847 lines (2267 loc) · 72.8 KB
/
Copy pathscpanel.cpp
File metadata and controls
2847 lines (2267 loc) · 72.8 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 <algorithm>
#include <cctype>
#include <cerrno>
#include <climits>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
#include <cwctype>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <ftw.h>
#include <glob.h>
#include <grp.h>
#include <iterator>
#include <map>
#include <ncurses.h>
#include <poll.h>
#include <pwd.h>
#include <set>
#include <sstream>
#include <string>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
/*
все что больше - передаем через rsync (нужен на двух серверах)
меняется в ~/.scpanel.config в rsync_from
*/
static const long long RSYNC_FROM_DEFAULT = 100LL * 1024 * 1024; // 100 МБ
static const long long RSYNC_NEVER = -1; // rsync_from = never - всегда scp
// клавиши можно переопределить в ~/.scpanel.config в секции [keys]
// name - как действие пишется в конфиге, keys - дефолт клавиши, help - строка помощи
enum Act
{
ACT_NONE,
ACT_UP,
ACT_DOWN,
ACT_PAGEUP,
ACT_PAGEDOWN,
ACT_HOME,
ACT_END,
ACT_PARENT,
ACT_OPEN,
ACT_PANEL,
ACT_MARK,
ACT_MARKALL,
ACT_SEND,
ACT_VIEW,
ACT_EDIT,
ACT_RENAME,
ACT_MKDIR,
ACT_NEWFILE,
ACT_DELETE,
ACT_GOTO,
ACT_SORT,
ACT_SEARCH,
ACT_NEXT,
ACT_PREV,
ACT_REFRESH,
ACT_HELP,
ACT_QUIT,
ACT_CANCEL, // работает только пока идет передача поэтому может делить действие с другими биндами
ACT_COUNT
};
struct ActionInfo
{ const char *name, *keys, *help; };
static const ActionInfo ACTIONS[ACT_COUNT] = {
{"", "", ""},
{"up", "Up", "move up"},
{"down", "Down", "move down"},
{"pageup", "PgUp", "page up"},
{"pagedown", "PgDn", "page down"},
{"home", "Home", "first item"},
{"end", "End", "last item"},
{"parent", "Left Backspace", "go to parent folder"},
{"open", "Enter Right", "open folder / send file"},
{"panel", "Tab", "other panel"},
{"mark", "Space", "mark"},
{"markall", "a", "mark all / unmark all"},
{"send", "s F5", "send to the other panel"},
{"view", "v F3", "view file"},
{"edit", "e F4", "edit file"},
{"rename", "m F6", "rename"},
{"mkdir", "f F7", "new folder"},
{"newfile", "c", "new empty file"},
{"delete", "d F8 Del", "delete"},
{"goto", "g", "go to path"},
{"sort", "o", "sort: name / date / size"},
{"search", "/", "search"},
{"next", "n", "next match"},
{"prev", "p", "previous match"},
{"refresh", "r", "refresh"},
{"help", "h F1", "this help"},
{"quit", "q Ctrl+C", "quit"},
{"cancel", "Esc q Ctrl+C", "cancel transfer (while it runs)"},
};
// недокачанное
static const char *PARTIAL_DIR = ".rsync-partial";
static const char *SORT_NAMES[] = {"name", "date (newest first)", "size (largest first)"};
// Ctrl+C во время передачи
static volatile sig_atomic_t g_cancel = 0;
static void onSigint(int)
{ g_cancel = 1; }
static std::string shq(const std::string &s)
{
std::string r = "'";
for (char c : s) r += (c == '\'') ? std::string("'\\''") : std::string(1, c);
return r + "'";
}
// "/home/user/x" -> "/home/user", "/home" -> "/"
static std::string parentOf(const std::string &path)
{
size_t pos = path.find_last_of('/');
if (pos == 0 || pos == std::string::npos)
return "/";
return path.substr(0, pos);
}
// чтобы в корне не получалось "//etc"
static std::string joinPath(const std::string &dir, const std::string &name)
{ return dir == "/" ? "/" + name : dir + "/" + name; }
// "/tmp" -> "/tmp/", "/" -> "/"
static std::string dirArg(const std::string &dir)
{ return dir == "/" ? "/" : dir + "/"; }
static std::string absolutePath(const std::string &path)
{
char buf[PATH_MAX];
if (realpath(path.c_str(), buf) == nullptr)
return "";
return buf;
}
static std::string trim(const std::string &s)
{
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos)
return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
// cтираем последний символ даже если это русская буква из двух байт
static void popUtf8(std::string &s)
{
while (!s.empty() && ((unsigned char)s.back() & 0xC0) == 0x80) s.pop_back();
if (!s.empty())
s.pop_back();
}
// 1536 -> "1.5K", 34000000 -> "32M"
static std::string humanSize(long long b)
{
const char units[] = "BKMGTP";
double v = (double)b;
int i = 0;
while (v >= 1024 && i < 5)
{
v /= 1024;
++i;
}
char buf[32];
if (i == 0)
snprintf(buf, sizeof(buf), "%lld", b);
else
snprintf(buf, sizeof(buf), v < 10 ? "%.1f%c" : "%.0f%c", v, units[i]);
return buf;
}
// то же но с "B" для небольших размеров
static std::string sizeText(long long b)
{ return humanSize(b) + (b < 1024 ? "B" : ""); }
// 1695481234 -> "2023-09-23 18:00"
static std::string formatDate(long long t)
{
if (t <= 0)
return "";
time_t tt = (time_t)t;
struct tm tm{};
localtime_r(&tt, &tm);
char buf[32];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", &tm);
return buf;
}
// 75 -> "1:15", 3725 -> "1:02:05"
static std::string formatDuration(double sec)
{
long long s = (long long)(sec + 0.5);
char buf[32];
if (s >= 3600)
snprintf(buf, sizeof(buf), "%lld:%02lld:%02lld", s / 3600, s / 60 % 60, s % 60);
else
snprintf(buf, sizeof(buf), "%lld:%02lld", s / 60, s % 60);
return buf;
}
// секунды с какого то момента
// чтобы мерить промежутки
static double nowSec()
{
struct timespec ts{};
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1e9;
}
// первая непустая строка
// в выводе scp/rsync/rm обычно сама ошибка
static std::string firstLine(const std::string &s)
{
std::istringstream iss(s);
std::string line;
while (std::getline(iss, line))
{
line = trim(line);
if (!line.empty())
return line;
}
return "";
}
static bool readFile(const std::string &path, std::string &out)
{
std::ifstream f(path, std::ios::binary);
if (!f)
return false;
out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
return true;
}
// проверка наличия в PATH
static bool inPath(const std::string &prog)
{
const char *env = getenv("PATH");
if (env == nullptr)
return false;
std::stringstream ss(env);
std::string dir;
while (std::getline(ss, dir, ':'))
{
if (dir.empty())
dir = ".";
if (access((dir + "/" + prog).c_str(), X_OK) == 0)
return true;
}
return false;
}
/*
русская буква - 2 байта но 1 клетка на экране
иероглиф - 2 клетки
обрезаем строки через подсчет клеток
проход по символам: f(с какого байта, сколько байт, сколько клеток, можно ли вывести)
*/
template <class F> static void forEachChar(const std::string &s, F f)
{
mbstate_t st{};
size_t i = 0;
while (i < s.size())
{
wchar_t wc = 0;
size_t n = mbrtowc(&wc, s.data() + i, s.size() - i, &st);
bool bad = (n == (size_t)-1 || n == (size_t)-2);
if (bad)
{
n = 1;
st = mbstate_t();
}
else if (n == 0)
n = 1;
int w = bad ? -1 : wcwidth(wc);
bool printable = !bad && w >= 0 && !iswcntrl(wc);
if (!f(i, n, printable ? w : 1, printable))
return;
i += n;
}
}
static int colsOf(const std::string &s)
{
int total = 0;
forEachChar(s, [&](size_t, size_t, int w, bool) {
total += w;
return true;
});
return total;
}
// подгон строки под кол-во клеток; длинную обрезаем с добавлением "…"; короткую добиваем пробелами
// символы которые невозможно вывести заменяем на "?"
static std::string fitCols(const std::string &s, int w)
{
if (w <= 0)
return "";
bool cut = colsOf(s) > w;
int limit = cut ? w - 1 : w;
std::string out;
int used = 0;
forEachChar(s, [&](size_t i, size_t n, int cw, bool printable) {
if (used + cw > limit)
return false;
if (printable)
out.append(s, i, n);
else
out += '?';
used += cw;
return true;
});
if (cut)
{
out += "…";
++used;
}
if (used < w)
out.append(w - used, ' ');
return out;
}
// поиск без учета регистра
static std::wstring lowerW(const std::string &s)
{
std::wstring out;
mbstate_t st{};
size_t i = 0;
while (i < s.size())
{
wchar_t wc = 0;
size_t n = mbrtowc(&wc, s.data() + i, s.size() - i, &st);
if (n == (size_t)-1 || n == (size_t)-2)
{
wc = (unsigned char)s[i];
n = 1;
st = mbstate_t();
}
else if (n == 0)
n = 1;
out += (wchar_t)towlower(wc);
i += n;
}
return out;
}
// запуск ssh/scp/rsync
static void execArgs(const std::vector<std::string> &args)
{
std::vector<char *> argv;
for (const auto &a : args) argv.push_back(const_cast<char *>(a.c_str()));
argv.push_back(nullptr);
execvp(argv[0], argv.data());
}
static int runCapture(const std::vector<std::string> &args, std::string *out)
{
int fd[2];
if (pipe(fd) != 0)
return -1;
pid_t pid = fork();
if (pid < 0)
{
close(fd[0]);
close(fd[1]);
return -1;
}
if (pid == 0)
{
int devnull = open("/dev/null", O_RDWR);
dup2(devnull, 0);
dup2(fd[1], 1);
dup2(devnull, 2);
close(fd[0]);
close(fd[1]);
execArgs(args);
_exit(127);
}
close(fd[1]);
char buf[65536];
for (;;)
{
ssize_t n = read(fd[0], buf, sizeof(buf));
if (n > 0)
{
if (out)
out->append(buf, n);
}
else if (n < 0 && errno == EINTR)
continue;
else
break;
}
close(fd[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
// то же но вход и выход берутся из файлов (inFd/outFd, -1 = /dev/null) а ошибки собираем в err
// таким образом скачиваем и заливаем файл через "ssh cat" без scp
static int runPiped(const std::vector<std::string> &args, int inFd, int outFd, std::string *err)
{
int ep[2];
if (pipe(ep) != 0)
return -1;
pid_t pid = fork();
if (pid < 0)
{
close(ep[0]);
close(ep[1]);
return -1;
}
if (pid == 0)
{
int devnull = open("/dev/null", O_RDWR);
dup2(inFd >= 0 ? inFd : devnull, 0);
dup2(outFd >= 0 ? outFd : devnull, 1);
dup2(ep[1], 2);
close(ep[0]);
close(ep[1]);
execArgs(args);
_exit(127);
}
close(ep[1]);
char buf[4096];
for (;;)
{
ssize_t n = read(ep[0], buf, sizeof(buf));
if (n > 0)
{
if (err)
err->append(buf, n);
}
else if (n < 0 && errno == EINTR)
continue;
else
break;
}
close(ep[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
// очистка экрана после завершения
static void clearIfNoAltScreen()
{
const char *smcup = tigetstr("smcup");
if (smcup != nullptr && smcup != (char *)-1 && *smcup)
return;
const char *cl = tigetstr("clear");
if (cl != nullptr && cl != (char *)-1)
putp(cl);
fflush(stdout);
}
static void leaveCurses()
{
endwin();
clearIfNoAltScreen();
}
// выход из интерфейса для ввода пароля и тд
static int runInTerminal(const std::vector<std::string> &args, const std::string &title)
{
def_prog_mode();
leaveCurses();
printf("\n%s\n", title.c_str());
fflush(stdout);
// Ctrl+C во время передачи отменяет ТОЛЬКО передачу
void (*oldInt)(int) = signal(SIGINT, SIG_IGN);
pid_t pid = fork();
if (pid == 0)
{
signal(SIGINT, SIG_DFL);
execArgs(args);
perror(args[0].c_str());
_exit(127);
}
int status = 0;
if (pid > 0)
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
signal(SIGINT, oldInt);
int rc = (pid < 0) ? -1 : (WIFEXITED(status) ? WEXITSTATUS(status) : -1);
if (rc != 0)
{
printf("\nFailed. Press Enter to go back...");
fflush(stdout);
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
}
reset_prog_mode();
clearok(stdscr, TRUE);
refresh();
return rc;
}
struct Entry
{
std::string name, owner, group;
char type = '?'; // d директория, l ссылка, f файл, ? хз
bool is_dir = false; // директория или ссылка на директорию
unsigned mode = 0; // права (755 и тд)
long long size = 0;
long long mtime = 0; // когда меняли, секунды с 1970
};
static std::string permString(char type, unsigned mode)
{
if (type == '?')
return "??????????";
std::string s(10, '-');
s[0] = (type == 'f') ? '-' : type;
const char rwx[] = "rwxrwxrwx";
for (int i = 0; i < 9; ++i)
if (mode & (0400u >> i))
s[i + 1] = rwx[i];
return s;
}
static char typeOf(mode_t m)
{
if (S_ISDIR(m))
return 'd';
if (S_ISLNK(m))
return 'l';
if (S_ISREG(m))
return 'f';
if (S_ISFIFO(m))
return 'p';
if (S_ISSOCK(m))
return 's';
if (S_ISCHR(m))
return 'c';
if (S_ISBLK(m))
return 'b';
return '?';
}
// Сначала директории потом файлы
// mode: 0 - по алфавиту, 1 - новые сверху, 2 - большие сверху
static void sortEntries(std::vector<Entry> &v, int mode)
{
std::sort(v.begin(), v.end(), [mode](const Entry &a, const Entry &b) {
if (a.is_dir != b.is_dir)
return a.is_dir;
if (mode == 1 && a.mtime != b.mtime)
return a.mtime > b.mtime;
if (mode == 2 && a.size != b.size)
return a.size > b.size;
return a.name < b.name;
});
}
static bool readLocalDir(const std::string &path, std::vector<Entry> &out, std::string &err)
{
DIR *dir = opendir(path.c_str());
if (dir == nullptr)
{
err = "Cannot open " + path + ": " + strerror(errno);
return false;
}
out.clear();
while (dirent *d = readdir(dir))
{
Entry e;
e.name = d->d_name;
if (e.name == "." || e.name == "..")
continue;
std::string full = joinPath(path, e.name);
struct stat lst{};
if (lstat(full.c_str(), &lst) == 0)
{
e.type = typeOf(lst.st_mode);
e.mode = lst.st_mode & 0777;
e.size = lst.st_size;
e.mtime = lst.st_mtime;
struct stat st{};
e.is_dir = e.type == 'd' || (e.type == 'l' && stat(full.c_str(), &st) == 0 && S_ISDIR(st.st_mode));
passwd *pw = getpwuid(lst.st_uid);
group *gr = getgrgid(lst.st_gid);
e.owner = pw ? pw->pw_name : std::to_string(lst.st_uid);
e.group = gr ? gr->gr_name : std::to_string(lst.st_gid);
}
out.push_back(e);
}
closedir(dir);
return true;
}
// размер файлов/директорий для выбора между scp и rsync
static long long g_sum = 0, g_limit = 0;
static int sumCallback(const char *, const struct stat *sb, int flag, struct FTW *)
{
if (flag == FTW_F)
g_sum += sb->st_size;
return g_sum >= g_limit ? 1 : 0;
}
static long long localSize(const std::vector<std::string> &paths, long long limit)
{
g_sum = 0;
g_limit = limit;
for (const auto &p : paths)
if (nftw(p.c_str(), sumCallback, 32, FTW_PHYS) == 1)
break;
return g_sum;
}
// удаление директории со всем содержимым
static int g_rmErrno = 0;
static int rmCallback(const char *path, const struct stat *, int, struct FTW *)
{
if (remove(path) == 0)
return 0;
g_rmErrno = errno;
return -1;
}
static bool removeLocal(const std::string &path, std::string &err)
{
g_rmErrno = 0;
if (nftw(path.c_str(), rmCallback, 32, FTW_DEPTH | FTW_PHYS) == 0)
return true;
err = path + ": " + strerror(g_rmErrno ? g_rmErrno : errno);
return false;
}
// логика как в mkdir -p
static bool makeDirs(const std::string &path, std::string &err)
{
for (size_t pos = 1; pos <= path.size(); ++pos)
{
if (pos != path.size() && path[pos] != '/')
continue;
std::string part = path.substr(0, pos);
if (mkdir(part.c_str(), 0777) != 0 && errno != EEXIST)
{
err = part + ": " + strerror(errno);
return false;
}
}
return true;
}
struct Target
{
std::string scp_host; // user@host или user@[::1] - формат scp и rsync
std::string ssh_host; // то же без квадратных скобок - формат ssh
std::string path; // директория на сервере, пусто = домашка
};
static Target parseTarget(const std::string &t)
{
Target r;
size_t from = t.rfind(']');
size_t colon = t.find(':', from == std::string::npos ? 0 : from);
r.scp_host = colon == std::string::npos ? t : t.substr(0, colon);
r.path = colon == std::string::npos ? "" : t.substr(colon + 1);
for (char c : r.scp_host)
if (c != '[' && c != ']')
r.ssh_host += c;
return r;
}
// настройка конфига
static std::string lower(std::string s)
{
for (char &c : s) c = (char)tolower((unsigned char)c);
return s;
}
static std::string homeDir()
{
const char *home = getenv("HOME");
return home ? home : "";
}
/*
имя клавиши из конфига -> коды которые отдает getch()
"s", "/" - сама буква; F1..F12; Ctrl+A..Ctrl+Z; Up Down Left Right PgUp PgDn Home End;
Enter Tab Space Esc Backspace Del Ins
*/
static std::vector<int> keyCodes(const std::string &name)
{
if (name.size() == 1 && isgraph((unsigned char)name[0]))
return {(unsigned char)name[0]};
std::string n = lower(name);
if (n.size() == 6 && n.compare(0, 5, "ctrl+") == 0 && isalpha((unsigned char)n[5]))
return {n[5] - 'a' + 1};
if (n.size() >= 2 && n[0] == 'f' && isdigit((unsigned char)n[1]))
{
int k = atoi(n.c_str() + 1);
if (k >= 1 && k <= 12 && n == "f" + std::to_string(k))
return {KEY_F(k)};
}
static const std::map<std::string, std::vector<int>> named = {
{"up", {KEY_UP}},
{"down", {KEY_DOWN}},
{"left", {KEY_LEFT}},
{"right", {KEY_RIGHT}},
{"pgup", {KEY_PPAGE}},
{"pgdn", {KEY_NPAGE}},
{"home", {KEY_HOME}},
{"end", {KEY_END}},
{"enter", {'\n', '\r', KEY_ENTER}},
{"tab", {'\t'}},
{"space", {' '}},
{"esc", {27}},
{"backspace", {KEY_BACKSPACE, 127, 8}}, // разные терминалы шлют разное
{"del", {KEY_DC}},
{"ins", {KEY_IC}},
};
auto it = named.find(n);
return it == named.end() ? std::vector<int>() : it->second;
}
struct Config
{
std::vector<std::string> keys[ACT_COUNT]; // имена клавиш для каждого действия (уже с учетом конфига)
std::map<int, int> keymap; // код клавиши -> действие (кроме cancel)
std::set<int> cancelKeys; // чем отменять передачу
int sort = 0; // см. sortEntries
long long rsyncFrom = RSYNC_FROM_DEFAULT; // с какого размера передавать через rsync
std::vector<std::string> warnings; // что в конфиге не поняли - покажем при запуске
};
static Config g_cfg;
static std::string configPath()
{ return homeDir() + "/.scpanel.config"; }
// Читаем ~/.scpanel.config. Нет файла - все по умолчанию.
// Если в [keys] действие указано, его клавиши по умолчанию заменяются целиком;
// пустое значение ("send =") - у действия вообще не будет клавиш.
static void loadConfig()
{
Config c;
bool custom[ACT_COUNT] = {};
for (int a = 1; a < ACT_COUNT; ++a)
{
std::istringstream iss(ACTIONS[a].keys);
for (std::string k; iss >> k;) c.keys[a].push_back(k);
}
std::ifstream f(configPath());
std::string line, section;
int no = 0;
while (std::getline(f, line))
{
++no;
line = trim(line);
if (line.empty() || line[0] == '#' || line[0] == ';')
continue;
std::string where = "~/.scpanel.config line " + std::to_string(no) + ": ";
if (line[0] == '[')
{
section = lower(trim(line.substr(1, line.find(']') - 1)));
if (section != "keys" && section != "options")
c.warnings.push_back(where + "unknown section [" + section + "]");
continue;
}
size_t eq = line.find('=');
if (eq == std::string::npos)
{
c.warnings.push_back(where + "expected name = value");
continue;
}
std::string name = lower(trim(line.substr(0, eq))), value = trim(line.substr(eq + 1));
if (section == "keys")
{
int a = 1;
while (a < ACT_COUNT && name != ACTIONS[a].name) ++a;
if (a == ACT_COUNT)
{
c.warnings.push_back(where + "unknown action '" + name + "'");
continue;
}
custom[a] = true;
c.keys[a].clear();
std::istringstream iss(value);
for (std::string k; iss >> k;)
{
if (keyCodes(k).empty())
c.warnings.push_back(where + "unknown key '" + k + "'");
else
c.keys[a].push_back(k);
}
}
else if (section == "options" && name == "sort")
{
std::string v = lower(value);
c.sort = v == "date" ? 1 : v == "size" ? 2 : 0;
if (v != "name" && v != "date" && v != "size")
c.warnings.push_back(where + "sort must be name, date or size");
}
else if (section == "options" && name == "rsync_from")
{
// "100M", "1G", "512K", "0" (всегда rsync), "never" (всегда scp)
std::string v = lower(value);
char *end = nullptr;
double n = strtod(v.c_str(), &end);
std::string unit = end ? trim(end) : "";
const std::map<std::string, double> mult = {{"", 1},
{"b", 1},
{"k", 1024},
{"m", 1024.0 * 1024},
{"g", 1024.0 * 1024 * 1024},
{"t", 1024.0 * 1024 * 1024 * 1024}};
if (v == "never")
c.rsyncFrom = RSYNC_NEVER;
else if (end == v.c_str() || n < 0 || !mult.count(unit))
c.warnings.push_back(where + "rsync_from must be a size like 100M, 1G, 0 or never");
else
c.rsyncFrom = (long long)(n * mult.at(unit));
}
else
c.warnings.push_back(where + "unknown setting '" + name + "'");
}
// Сначала раскладываем клавиши по умолчанию, потом - из конфига: если клавиша из конфига
// уже занята другим действием, побеждает конфиг
for (int pass = 0; pass < 2; ++pass)
for (int a = 1; a < ACT_CANCEL; ++a)
if (custom[a] == (pass == 1))
for (const auto &k : c.keys[a])
for (int code : keyCodes(k)) c.keymap[code] = a;
// у действий, у которых конфиг забрал клавишу, убираем ее и из подсказок
for (int a = 1; a < ACT_CANCEL; ++a)
{
std::vector<std::string> kept;
for (const auto &k : c.keys[a])
if (c.keymap[keyCodes(k)[0]] == a)
kept.push_back(k);
c.keys[a].swap(kept);
}
for (const auto &k : c.keys[ACT_CANCEL])
for (int code : keyCodes(k)) c.cancelKeys.insert(code);
g_cfg = c;
}
static int actionFor(int ch)
{
auto it = g_cfg.keymap.find(ch);
return it == g_cfg.keymap.end() ? ACT_NONE : it->second;
}