-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.cpp
4325 lines (3545 loc) · 107 KB
/
main.cpp
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 <iostream>
#include <fstream>
#include <sstream>
#include <atomic>
#include <deque>
#include <queue>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <memory>
#include <array>
#include <linux/fs.h>
#include <sys/syscall.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <termios.h>
#include <dirent.h>
#include <locale.h>
#include <unistd.h>
#include <signal.h>
#include <regex.h>
#include <fcntl.h>
#include <langinfo.h>
#include <iconv.h>
#include <uchardet/uchardet.h>
#include <taglib/fileref.h>
#include <taglib/tdebuglistener.h>
#include "./termbox/termbox.h"
#include "./libbsd/strmode.h"
#include "./inih/INIReader.h"
#include "./tsl/robin_set.h"
#include "./cpp-linenoise/linenoise.hpp"
#include "./cmdline/cmdline.h"
#include "NanoSyntaxHighlight.hpp"
#include "ImageUtil.hpp"
#include "TermboxUtil.hpp"
#include "help.hpp"
#include "icons.hpp"
const static int TAB_MAX = 4;
static const char* const TMP_FILENAME = "/tmp/minase_tmp";
class NullListener : public TagLib::DebugListener {
public:
virtual void printMessage(const TagLib::String &msg) {(void)msg;}
};
static std::string getBaseName(const std::string& name)
{
auto pos = name.find_last_of('/');
if(pos != std::string::npos)
return name.substr(name.find_last_of('/') + 1);
return "";
}
static std::string getDirName(const std::string& name)
{
auto pos = name.find_last_of('/');
if(pos != std::string::npos)
return name.substr(0, name.find_last_of('/'));
return "";
}
static std::string getSuffix(const std::string &name)
{
auto i = name.find_last_of(".");
if(i == 0) return "";
if(i == std::string::npos) return "";
return name.substr(i + 1, name.size() - i);
}
#ifdef USE_MIGEMO
#include <migemo.h>
migemo* mgm;
static const char* DEFAULT_MIGEMO_DICT = "/usr/share/migemo/utf-8/migemo-dict";
/*
+https://github.com/koron/cmigemo
+ charset.c: utf8_int2char
+ rxgen.c: default_int2char
+
+ Copyright (c) 2003-2007 MURAOKA Taro (KoRoN)
+ Released under the MIT license
+ URL: https://github.com/koron/cmigemo/blob/master/doc/LICENSE_MIT.txt
+
+ UTF8 + PCRE用に改変
+*/
static int utf8pcre_int2char(unsigned int in, unsigned char* out)
{
if(in < 0x80) {
int len = 0;
/* outは最低でも16バイトはある、という仮定を置く */
switch(in) {
case '\\':
case '.': case '*': case '^': case '$': case '/':
case ' ': case '(': case ')': case '+':
case '-': case '?': case '[': case ']': case '{':
case '|': case '}':
if(out) out[len] = '\\';
++len;
default:
if(out) out[len] = (unsigned char)(in & 0xFF);
++len;
break;
}
return len;
}
if(in < 0x800) {
if(out) {
out[0] = 0xc0 + (in >> 6);
out[1] = 0x80 + ((in >> 0) & 0x3f);
}
return 2;
}
if(in < 0x10000) {
if(out) {
out[0] = 0xe0 + (in >> 12);
out[1] = 0x80 + ((in >> 6) & 0x3f);
out[2] = 0x80 + ((in >> 0) & 0x3f);
}
return 3;
}
if(in < 0x200000) {
if(out) {
out[0] = 0xf0 + (in >> 18);
out[1] = 0x80 + ((in >> 12) & 0x3f);
out[2] = 0x80 + ((in >> 6) & 0x3f);
out[3] = 0x80 + ((in >> 0) & 0x3f);
}
return 4;
}
if(in < 0x4000000) {
if(out) {
out[0] = 0xf8 + (in >> 24);
out[1] = 0x80 + ((in >> 18) & 0x3f);
out[2] = 0x80 + ((in >> 12) & 0x3f);
out[3] = 0x80 + ((in >> 6) & 0x3f);
out[4] = 0x80 + ((in >> 0) & 0x3f);
}
return 5;
}
else {
if(out) {
out[0] = 0xf8 + (in >> 30);
out[1] = 0x80 + ((in >> 24) & 0x3f);
out[2] = 0x80 + ((in >> 18) & 0x3f);
out[3] = 0x80 + ((in >> 12) & 0x3f);
out[4] = 0x80 + ((in >> 6) & 0x3f);
out[5] = 0x80 + ((in >> 0) & 0x3f);
}
return 6;
}
}
/*-end-*/
#endif
class Config {
public:
Config() : logMaxlines_(100), preViewMaxlines_(50), fileViewType_(0),
sortType_(0), sortOrder_(0),
useTrash_(false), wcwidthCJK_(false),
nanorcPath_("/usr/share/nano"), opener_("xdg-open"),
archiveMntDir_("~/.config/Minase/mnt")
{}
bool LoadConfig(const std::string& fileName) {
INIReader reader(fileName);
if(reader.ParseError() != 0) {
std::cerr << "Can't load : " << fileName << std::endl;;
return false;
}
logMaxlines_ = reader.GetInteger("Options", "LogMaxLines", 100);
preViewMaxlines_ = reader.GetInteger("Options", "PreViewMaxLines", 50);
useTrash_ = reader.GetBoolean("Options", "UseTrash", false);
nanorcPath_ = reader.Get("Options", "NanorcPath", "/usr/share/nano");
wcwidthCJK_ = reader.GetBoolean("Options", "wcwidth-cjk", false);
opener_ = reader.Get("Options", "Opener", "xdg-open");
fileViewType_ = reader.GetInteger("Options", "FileViewType", 0);
sortType_ = reader.GetInteger("Options", "SortType", 0);
sortOrder_ = reader.GetInteger("Options", "SortOrder", 0);
filterType_ = reader.GetInteger("Options", "FilterType", 0);
archiveMntDir_ = reader.Get("Options", "ArchiveMntDir", "~/.config/Minase/mnt");
customCopy_ = reader.Get("Options", "CustomCopy", "");
customMove_ = reader.Get("Options", "CustomMove", "");
customRenamer_ = reader.Get("Options", "CustomRenamer", "");
icon_ = reader.GetBoolean("Options", "UseIcon", false);
#ifdef USE_MIGEMO
migemoDict_ = reader.Get("Options", "MigemoDict", DEFAULT_MIGEMO_DICT);
#endif
return true;
}
bool LoadBookmarks(const std::string& fileName) {
FILE* fp;
if((fp = fopen(fileName.c_str(), "r")) == NULL)
return false;
char buf[4096];
while(!feof(fp)) {
if(fgets(buf, sizeof(buf), fp) != 0) {
std::string bookmark(buf);
if(!bookmark.empty() && bookmark.back() == '\n') bookmark.pop_back();
if(!bookmark.empty() && bookmark.back() == '\r') bookmark.pop_back();
bookmarks_.emplace_back(bookmark);
}
}
fclose(fp);
return true;
}
struct Plugin {
bool gui;
std::string name;
std::string filePath;
std::string key;
bool inputText;
bool silent;
enum Operation {
NONE,
CHANGE_DIRECTORY,
CHANGE_CURRENT_FILE,
};
Operation operation;
};
bool LoadPlugins(const std::string& fileName) {
INIReader reader(fileName);
if(reader.ParseError() != 0) {
std::cerr << "Can't load : " << fileName << std::endl;;
return false;
}
auto sections = reader.Sections();
for(auto const& section : sections) {
Plugin p;
p.name = section;
p.filePath = reader.Get(section, "filePath", "");
p.gui = reader.GetBoolean(section, "gui", false);
p.key = reader.Get(section, "key", "");
p.inputText = false;
if(!p.filePath.empty()) {
auto basename = getBaseName(p.filePath);
if(!basename.empty()) {
char op = basename[0];
if(basename[0] == '_') {
p.inputText = true;
if(basename.length() > 2) op = basename[1];
}
p.silent = (basename.back() == '%');
switch(op) {
case '0':
p.operation = Plugin::Operation::NONE;
break;
case '1':
p.operation = Plugin::Operation::CHANGE_DIRECTORY;
p.gui = false;
break;
case '2':
p.operation = Plugin::Operation::CHANGE_CURRENT_FILE;
p.gui = false;
break;
default:
p.operation = Plugin::Operation::NONE;
};
}
}
plugins_.emplace_back(p);
}
return true;
}
int getLogMaxLines() const { return logMaxlines_; }
int getPreViewMaxLines() const { return preViewMaxlines_; }
int getFileViewType() const { return fileViewType_; }
int getSortType() const { return sortType_; }
int getSortOrder() const { return sortOrder_; }
int getFilterType() const { return filterType_; }
std::string getArchiveMntDir() const { return archiveMntDir_; }
#ifdef USE_MIGEMO
std::string getMigemoDict() const { return migemoDict_; }
#endif
bool useTrash() const { return useTrash_; }
bool wcwidthCJK() const { return wcwidthCJK_; }
std::string getNanorcPath() const { return nanorcPath_; }
std::string getOpener() const { return opener_; }
std::vector<std::string> getBookmarks() const { return bookmarks_; }
std::vector<Plugin> getPlugins() const { return plugins_; }
std::string getCustomCopy() const { return customCopy_; }
std::string getCustomMove() const { return customMove_; }
std::string getCustomRenamer() const { return customRenamer_; }
bool useIcon() const { return icon_; }
private:
int logMaxlines_;
int preViewMaxlines_;
int fileViewType_;
int sortType_, sortOrder_;
int filterType_;
bool useTrash_;
bool wcwidthCJK_;
bool icon_;
std::string nanorcPath_, opener_, archiveMntDir_;
std::vector<std::string> bookmarks_;
std::vector<Plugin> plugins_;
std::string customCopy_, customMove_, customRenamer_;
#ifdef USE_MIGEMO
std::string migemoDict_;
#endif
};
Config config;
int spawn(const std::string& cmd, const std::string& args1,
const std::string& args2, const std::string& args3,
const std::string& dir, bool gui = false, bool silent = false)
{
bool chDir = dir.empty() ? false : true;
pid_t pid;
if(!gui) {
if(!silent) tb_shutdown();
pid = fork();
if(pid < 0) return -1;
else if(pid == 0) {
if(chDir) chdir(dir.c_str());
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
execlp(cmd.c_str(), cmd.c_str(),
args1.empty() ? NULL : args1.c_str(),
args2.empty() ? NULL : args2.c_str(),
args3.empty() ? NULL : args3.c_str(),
NULL);
_exit(1);
}
int stat = 0;
waitpid(pid, &stat, 0);
if(WIFSIGNALED(stat)) printf("\n");
if(!silent) tb_init();
if(WIFEXITED(stat)) {
return WEXITSTATUS(stat);
}
}
else {
pid = fork();
if(pid < 0) return -1;
else if(pid == 0) {
pid_t pid2 = fork();
if(pid2 < 0) _exit(1);
else if(pid2 == 0) {
if(chDir) chdir(dir.c_str());
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
setsid();
int fd = open("/dev/null", O_WRONLY, 0200);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
execlp(cmd.c_str(), cmd.c_str(),
args1.empty() ? NULL : args1.c_str(),
args2.empty() ? NULL : args2.c_str(),
args3.empty() ? NULL : args3.c_str(),
NULL);
_exit(1);
}
_exit(0);
}
int stat = 0;
waitpid(pid, &stat, 0);
}
return 0;
}
pid_t popen2(const std::string& cmd,
const std::vector<std::string>& args, int *infp, int *outfp, bool stderr_out = false)
{
int p_stdin[2], p_stdout[2];
pid_t pid;
if(pipe(p_stdin) != 0)
return -1;
if(pipe(p_stdout) != 0) {
close(p_stdin[0]);
close(p_stdin[1]);
return -1;
}
std::vector<char*> argc;
argc.emplace_back(const_cast<char*>(cmd.c_str()));
for(auto const& s : args)
argc.emplace_back(const_cast<char*>(s.c_str()));
argc.push_back(0);
pid = fork();
if(pid < 0) {
close(p_stdin[0]);
close(p_stdin[1]);
close(p_stdout[0]);
close(p_stdout[1]);
return pid;
}
else if(pid == 0) {
dup2(p_stdin[0], STDIN_FILENO);
dup2(p_stdout[1], STDOUT_FILENO);
if(stderr_out) dup2(p_stdout[1], STDERR_FILENO);
else {
int fd = open("/dev/null", O_WRONLY, 0200);
dup2(fd, STDERR_FILENO);
close(fd);
}
close(p_stdin[0]);
close(p_stdin[1]);
close(p_stdout[0]);
close(p_stdout[1]);
execvp(cmd.c_str(), argc.data());
perror("execvp");
_exit(1);
}
close(p_stdin[0]);
close(p_stdout[1]);
if(infp == NULL) close(p_stdin[1]);
else *infp = p_stdin[1];
if(outfp == NULL) close(p_stdout[0]);
else *outfp = p_stdout[0];
return pid;
}
int pclose2(pid_t pid)
{
int stat;
waitpid(pid, &stat, 0);
return WEXITSTATUS(stat);
}
bool which(std::string cmd)
{
auto shell = getenv("SHELL");
if(shell == 0) return false;
if(spawn(shell, "-c", "which " + cmd + " > /dev/null", "", "", false, true) == 0)
return true;
else return false;
}
class FileInfo {
public:
FileInfo(const std::string& path, const std::string& fileName) :
path_(path), name_(fileName) {
if(!path.empty()) {
lstat(std::string(path_ + name_).c_str(), &lstat_);
if(S_ISDIR(lstat_.st_mode)) dir_ = true;
else if(S_ISLNK(lstat_.st_mode)) {
struct stat s;
stat(std::string(path_ + name_).c_str(), &s);
dir_ = S_ISDIR(s.st_mode);
}
else dir_ = false;
if(isDir()) name_ += '/';
}
}
std::string getFileName() const { return name_; }
std::string getPath() const { return path_; }
std::string getFilePath() const { return path_ + name_; }
std::string getSuffix() const {
if(isDir()) return "";
return ::getSuffix(name_);
}
bool isDir() const { return dir_; }
bool isLink() const { return S_ISLNK(lstat_.st_mode); }
bool isFifo() const { return S_ISFIFO(lstat_.st_mode); }
bool isSock() const { return S_ISSOCK(lstat_.st_mode); }
bool isExe() const {
if(S_ISREG(lstat_.st_mode))
return lstat_.st_mode & S_IXUSR;
return false;
}
mode_t getMode() const { return lstat_.st_mode; }
off_t getSize() const { return lstat_.st_size; }
timespec getMTime() const { return lstat_.st_mtim; }
static std::string getModeStr(const FileInfo& fileInfo) {
char strMode[80];
strmode(fileInfo.getMode(), strMode);
return strMode;
}
static std::string getMTimeStr(const FileInfo& fileInfo) {
struct tm tm;
auto mtim = fileInfo.getMTime();
localtime_r(&mtim.tv_sec, &tm);
char buf[256];
snprintf(buf, sizeof(buf), "%04d/%02d/%02d %02d:%02d:%02d",
tm.tm_year + 1900, tm.tm_mon + 1,
tm.tm_mday, tm.tm_hour,
tm.tm_min, tm.tm_sec);
return std::string(buf);
}
/*
* https://github.com/jarun/nnn
* nnn.c: char *coolsize(off_t size)
*
* BSD 2-Clause License
*
* Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
* Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
* Copyright (C) 2016-2019, Arun Prakash Jana <engineerarun@gmail.com>
* All rights reserved.
*/
static std::string getSizeStr(const FileInfo& fileInfo) {
auto size = fileInfo.getSize();
static const char * const U = "BKMGTPEZY";
static char size_buf[12]; /* Buffer to hold human readable size */
static off_t rem;
static int i;
rem = i = 0;
while (size > 1024) {
rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
size >>= 10;
++i;
}
if (i == 1) {
rem = (rem * 1000) >> 10;
rem /= 10;
if (rem % 10 >= 5) {
rem = (rem / 10) + 1;
if (rem == 10) {
++size;
rem = 0;
}
} else
rem /= 10;
} else if (i == 2) {
rem = (rem * 1000) >> 10;
if (rem % 10 >= 5) {
rem = (rem / 10) + 1;
if (rem == 100) {
++size;
rem = 0;
}
} else
rem /= 10;
} else if (i > 0) {
rem = (rem * 10000) >> 10;
if (rem % 10 >= 5) {
rem = (rem / 10) + 1;
if (rem == 1000) {
++size;
rem = 0;
}
} else
rem /= 10;
}
if (i > 0 && i < 6)
snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
else
snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
return std::string(size_buf);
}
/*-end-*/
private:
std::string path_;
std::string name_;
struct stat lstat_;
bool dir_;
};
class DirInfo {
public:
DirInfo(const std::string& path, std::atomic<bool>* kill = 0):
hidden_(false), sortType_(SortType::NAME), sortOrder_(SortOrder::ASCENDING), filterType_(FilterType::NORMAL) {
switch(config.getSortType()) {
case 0:
sortType_ = SortType::NAME;
break;
case 1:
sortType_ = SortType::SIZE;
break;
case 2:
sortType_ = SortType::DATE;
break;
};
if(config.getSortOrder() == 0) sortOrder_ = SortOrder::ASCENDING;
else sortOrder_ = SortOrder::DESCENDING;
switch(config.getFilterType()) {
case 0:
filterType_ = FilterType::NORMAL;
break;
case 1:
filterType_ = FilterType::REGEXP;
break;
#ifdef USE_MIGEMO
case 2:
filterType_ = FilterType::MIGEMO;
break;
#endif
};
chdir(path, kill);
}
bool chdir(const std::string& path, std::atomic<bool>* kill = 0) {
if(path_ != path) filter_ = "";
path_ = path;
fileList_.clear();
filteredFileList_.clear();
auto dir = opendir(path.c_str());
if(dir == NULL) return false;
struct dirent* dp;
while((dp = readdir(dir)) != NULL) {
if((dp -> d_name[0] == '.' && (dp -> d_name[1] == 0 || (dp -> d_name[1] == '.' && dp -> d_name[2] == 0))))
continue;
if(kill != 0 && *kill==true) {
closedir(dir);
return false;
}
std::shared_ptr<FileInfo> fileInfo(new FileInfo(path_, dp -> d_name));
fileList_.emplace_back(fileInfo);
}
closedir(dir);
filteredFileList();
return true;
}
void showHiddenFiles(bool flg) {
if(hidden_ != flg) {
hidden_ = flg;
filteredFileList();
}
}
bool isShowHiddenFiles() const { return hidden_; }
int getCount() const { return filteredFileList_.size(); }
FileInfo at(int index) const { return *filteredFileList_[index]; }
enum SortType {
NAME,
SIZE,
DATE,
};
enum SortOrder {
ASCENDING,
DESCENDING,
};
enum FilterType {
NORMAL,
REGEXP,
#ifdef USE_MIGEMO
MIGEMO,
#endif
};
void sort(SortType type, SortOrder order) {
if(sortType_ != type || sortOrder_ != order) {
sortType_ = type;
sortOrder_ = order;
filteredFileList();
}
}
SortType getSortType() const { return sortType_; }
SortOrder getSortOrder() const { return sortOrder_; }
void filter(const std::string& filter, FilterType type) {
filter_ = filter;
filterType_ = type;
filteredFileList();
}
std::string getFilter() const {
return filter_;
}
FilterType getFilterType() const {
return filterType_;
}
private:
class Filter {
public:
Filter() {}
virtual ~Filter() {}
virtual bool isMatch(const std::string& fileName) { (void)fileName; return true; };
};
class NormalFilter : public Filter {
public:
NormalFilter(const std::string& filter) {
std::stringstream ss{filter};
std::string buf;
while(std::getline(ss, buf, ' ')) {
std::transform(buf.cbegin(), buf.cend(), buf.begin(), toupper);
filters_.push_back(buf);
}
}
~NormalFilter() {}
bool isMatch(const std::string& fileName) {
std::string uFileName;
uFileName.resize(fileName.size());
std::transform(fileName.cbegin(), fileName.cend(), uFileName.begin(), toupper);
for(auto filter: filters_) {
if(uFileName.find(filter) == std::string::npos) return false;
}
return true;
}
private:
std::vector<std::string> filters_;
};
class RegexpFilter : public Filter {
public:
RegexpFilter(const std::string& filter) : reg_(false) {
if(regcomp(&re_, filter.c_str(),
REG_EXTENDED|REG_NEWLINE|REG_NOSUB|REG_ICASE) == 0) reg_ = true;
}
~RegexpFilter() { if(reg_) regfree(&re_); }
bool isMatch(const std::string& fileName) {
if(!reg_) return true;
if(!(regexec(&re_, fileName.c_str(), 0, m_, 0) != REG_NOMATCH))
return false;
return true;
}
private:
bool reg_;
regex_t re_;
regmatch_t m_[1];
};
#ifdef USE_MIGEMO
class MigemoFilter : public Filter {
public:
MigemoFilter(const std::string& filter) {
std::vector<std::string> filters;
std::stringstream ss{filter};
std::string buf;
while(std::getline(ss, buf, ' ')) {
std::transform(buf.cbegin(), buf.cend(), buf.begin(), toupper);
filters.push_back(buf);
}
for(auto s: filters) {
unsigned char* migemo_re = migemo_query(mgm, (unsigned char*)s.c_str());
regex_t re;
regcomp(&re, (char*)migemo_re,
REG_EXTENDED|REG_NEWLINE|REG_NOSUB|REG_ICASE);
filtersRegex_.emplace_back(re);
}
}
~MigemoFilter() {
for(auto re: filtersRegex_) regfree(&re);
}
bool isMatch(const std::string& fileName) {
for(auto re: filtersRegex_) {
if(!(regexec(&re, fileName.c_str(), 0, m_, 0) != REG_NOMATCH)) return false;
}
return true;
}
private:
std::vector<regex_t> filtersRegex_;
regmatch_t m_[1];
};
#endif
void filteredFileList() {
filteredFileList_.clear();
std::unique_ptr<Filter> filterFunc(new Filter);
if(!filter_.empty()) {
switch(filterType_) {
case NORMAL:
filterFunc.reset(new NormalFilter(filter_));
break;
case REGEXP:
filterFunc.reset(new RegexpFilter(filter_));
break;
#ifdef USE_MIGEMO
case MIGEMO:
filterFunc.reset(new MigemoFilter(filter_));
break;
#endif
};
}
for(auto&& file: fileList_) {
if(!(filterFunc -> isMatch(file -> getFileName()))) continue;
if(!hidden_) {
if(file -> getFileName()[0] != '.')
filteredFileList_.emplace_back(file);
}
else filteredFileList_.emplace_back(file);
}
sortList();
}
void sortList() {
typedef std::shared_ptr<FileInfo> FileInfo_Ptr;
std::function<bool(const FileInfo_Ptr&, const FileInfo_Ptr&)> func;
switch(sortType_) {
case SortType::NAME:
func = [](const FileInfo_Ptr& a, const FileInfo_Ptr& b)
{ return a -> getFileName() < b -> getFileName(); };
break;
case SortType::SIZE:
func = [](const FileInfo_Ptr& a, const FileInfo_Ptr& b) {
if(a -> getSize() == b -> getSize())
return a -> getFileName() < b -> getFileName();
else
return a -> getSize() < b -> getSize();
};
break;
case SortType::DATE:
func = [](const FileInfo_Ptr& a, const FileInfo_Ptr& b) {
auto at = a -> getMTime();
auto bt = b -> getMTime();
if (at.tv_sec == bt.tv_sec) {
if (at.tv_nsec == bt.tv_nsec)
return a -> getFileName() < b -> getFileName();
else
return at.tv_nsec < bt.tv_nsec;
}
else
return at.tv_sec < bt.tv_sec;
};
break;
};
if(sortOrder_ == SortOrder::DESCENDING)
func = std::bind(func, std::placeholders::_2, std::placeholders::_1);
std::sort(filteredFileList_.begin(), filteredFileList_.end(),
[func](const FileInfo_Ptr& a, const FileInfo_Ptr& b) {
if(a -> isDir() && b -> isDir())
return func(a, b);
else if(a -> isDir() && !b -> isDir())
return true;
else if(!a -> isDir() && b -> isDir())
return false;
else return func(a, b);;
});
}
bool hidden_;
std::string path_, filter_;
std::vector<std::shared_ptr<FileInfo>> fileList_;
std::vector<std::shared_ptr<FileInfo>> filteredFileList_;
SortType sortType_;
SortOrder sortOrder_;
FilterType filterType_;
};
class CheckFileType {
public:
static bool isImage(FILE* fp) {
fseek(fp, 0L, SEEK_SET);
if(ImageUtil::checkHeader(fp) != ImageUtil::IMG_TYPE::IMG_UNKNOWN) {
fseek(fp, 0L, SEEK_SET);
return true;
}
fseek(fp, 0L, SEEK_SET);
return false;
}
static bool isPDF(FILE* fp) {
fseek(fp, 0L, SEEK_SET);
unsigned char header[4];
fread(header, 1, sizeof(header), fp);
fseek(fp, 0L, SEEK_SET);
if(header[0] == '%' && header[1] == 'P' &&
header[2] == 'D' && header[3] == 'F') {
return true;
}
return false;
}
static bool isSixel(FILE* fp) {
fseek(fp, 0L, SEEK_SET);
unsigned char header[3];
fread(header, 1, sizeof(header), fp);
fseek(fp, 0L, SEEK_SET);
if(header[0] == 0x1B && header[1] == 0x50) {
return true;
}
return false;
}
static bool isAudio(const FileInfo& fileInfo) {
auto suffix = fileInfo.getSuffix();
std::transform(suffix.begin(), suffix.end(), suffix.begin(), tolower);