-
Notifications
You must be signed in to change notification settings - Fork 200
/
ImGuiFileDialog.cpp
5157 lines (4575 loc) · 208 KB
/
ImGuiFileDialog.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
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/*
MIT License
Copyright (c) 2019-2024 Stephane Cuillerdier (aka aiekick)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "ImGuiFileDialog.h"
#ifdef __cplusplus
#include <cstring> // stricmp / strcasecmp
#include <cstdarg> // variadic
#include <sstream>
#include <iomanip>
#include <ctime>
#include <memory>
#include <sys/stat.h>
#include <cstdio>
#include <cerrno>
// this option need c++17
#ifdef USE_STD_FILESYSTEM
#include <filesystem>
#include <exception>
#endif // USE_STD_FILESYSTEM
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif // __EMSCRIPTEN__
#ifdef _MSC_VER
#define IGFD_DEBUG_BREAK \
if (IsDebuggerPresent()) __debugbreak()
#else
#define IGFD_DEBUG_BREAK
#endif
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
#define _IGFD_WIN_
#define stat _stati64
#define stricmp _stricmp
#include <cctype>
// this option need c++17
#ifdef USE_STD_FILESYSTEM
#include <windows.h>
#else
#include "dirent/dirent.h" // directly open the dirent file attached to this lib
#endif // USE_STD_FILESYSTEM
#define PATH_SEP '\\'
#ifndef PATH_MAX
#define PATH_MAX 260
#endif // PATH_MAX
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__EMSCRIPTEN__)
#define _IGFD_UNIX_
#define stricmp strcasecmp
#include <sys/types.h>
// this option need c++17
#ifndef USE_STD_FILESYSTEM
#include <dirent.h>
#endif // USE_STD_FILESYSTEM
#define PATH_SEP '/'
#endif // _IGFD_UNIX_
#include "imgui.h"
#include "imgui_internal.h"
// legacy compatibility 1.89
#ifndef IM_TRUNC
#define IM_TRUNC IM_FLOOR
#endif
#include <cstdlib>
#include <algorithm>
#include <iostream>
///////////////////////////////
// STB IMAGE LIBS
///////////////////////////////
#ifdef USE_THUMBNAILS
#ifndef DONT_DEFINE_AGAIN__STB_IMAGE_IMPLEMENTATION
#ifndef STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#endif // STB_IMAGE_IMPLEMENTATION
#endif // DONT_DEFINE_AGAIN__STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#ifndef DONT_DEFINE_AGAIN__STB_IMAGE_RESIZE_IMPLEMENTATION
#ifndef STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#endif // STB_IMAGE_RESIZE_IMPLEMENTATION
#endif // DONT_DEFINE_AGAIN__STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb/stb_image_resize2.h"
#endif // USE_THUMBNAILS
///////////////////////////////
// FLOAT MACROS
///////////////////////////////
// float comparisons
#ifndef IS_FLOAT_DIFFERENT
#define IS_FLOAT_DIFFERENT(a, b) (fabs((a) - (b)) > FLT_EPSILON)
#endif // IS_FLOAT_DIFFERENT
#ifndef IS_FLOAT_EQUAL
#define IS_FLOAT_EQUAL(a, b) (fabs((a) - (b)) < FLT_EPSILON)
#endif // IS_FLOAT_EQUAL
///////////////////////////////
// COMBOBOX
///////////////////////////////
#ifndef FILTER_COMBO_AUTO_SIZE
#define FILTER_COMBO_AUTO_SIZE 1
#endif // FILTER_COMBO_AUTO_SIZE
#ifndef FILTER_COMBO_MIN_WIDTH
#define FILTER_COMBO_MIN_WIDTH 150.0f
#endif // FILTER_COMBO_MIN_WIDTH
#ifndef IMGUI_BEGIN_COMBO
#define IMGUI_BEGIN_COMBO ImGui::BeginCombo
#endif // IMGUI_BEGIN_COMBO
///////////////////////////////
// BUTTON
///////////////////////////////
// for lets you define your button widget
// if you have like me a special bi-color button
#ifndef IMGUI_PATH_BUTTON
#define IMGUI_PATH_BUTTON ImGui::Button
#endif // IMGUI_PATH_BUTTON
#ifndef IMGUI_BUTTON
#define IMGUI_BUTTON ImGui::Button
#endif // IMGUI_BUTTON
///////////////////////////////
// locales
///////////////////////////////
#ifndef createDirButtonString
#define createDirButtonString "+"
#endif // createDirButtonString
#ifndef okButtonString
#define okButtonString "OK"
#endif // okButtonString
#ifndef okButtonWidth
#define okButtonWidth 0.0f
#endif // okButtonWidth
#ifndef cancelButtonString
#define cancelButtonString "Cancel"
#endif // cancelButtonString
#ifndef cancelButtonWidth
#define cancelButtonWidth 0.0f
#endif // cancelButtonWidth
#ifndef okCancelButtonAlignement
#define okCancelButtonAlignement 0.0f
#endif // okCancelButtonAlignement
#ifndef invertOkAndCancelButtons
// 0 => disabled, 1 => enabled
#define invertOkAndCancelButtons 0
#endif // invertOkAndCancelButtons
#ifndef resetButtonString
#define resetButtonString "R"
#endif // resetButtonString
#ifndef devicesButtonString
#define devicesButtonString "Devices"
#endif // devicesButtonString
#ifndef editPathButtonString
#define editPathButtonString "E"
#endif // editPathButtonString
#ifndef searchString
#define searchString "Search :"
#endif // searchString
#ifndef dirEntryString
#define dirEntryString "[Dir]"
#endif // dirEntryString
#ifndef linkEntryString
#define linkEntryString "[Link]"
#endif // linkEntryString
#ifndef fileEntryString
#define fileEntryString "[File]"
#endif // fileEntryString
#ifndef fileNameString
#define fileNameString "File Name:"
#endif // fileNameString
#ifndef dirNameString
#define dirNameString "Directory Path:"
#endif // dirNameString
#ifndef buttonResetSearchString
#define buttonResetSearchString "Reset search"
#endif // buttonResetSearchString
#ifndef buttonDriveString
#define buttonDriveString "Devices"
#endif // buttonDriveString
#ifndef buttonEditPathString
#define buttonEditPathString "Edit path\nYou can also right click on path buttons"
#endif // buttonEditPathString
#ifndef buttonResetPathString
#define buttonResetPathString "Reset to current directory"
#endif // buttonResetPathString
#ifndef buttonCreateDirString
#define buttonCreateDirString "Create Directory"
#endif // buttonCreateDirString
#ifndef tableHeaderAscendingIcon
#define tableHeaderAscendingIcon "A|"
#endif // tableHeaderAscendingIcon
#ifndef tableHeaderDescendingIcon
#define tableHeaderDescendingIcon "D|"
#endif // tableHeaderDescendingIcon
#ifndef tableHeaderFileNameString
#define tableHeaderFileNameString "File name"
#endif // tableHeaderFileNameString
#ifndef tableHeaderFileTypeString
#define tableHeaderFileTypeString "Type"
#endif // tableHeaderFileTypeString
#ifndef tableHeaderFileSizeString
#define tableHeaderFileSizeString "Size"
#endif // tableHeaderFileSizeString
#ifndef tableHeaderFileDateString
#define tableHeaderFileDateString "Date"
#endif // tableHeaderFileDateString
#ifndef fileSizeBytes
#define fileSizeBytes "o"
#endif // fileSizeBytes
#ifndef fileSizeKiloBytes
#define fileSizeKiloBytes "Ko"
#endif // fileSizeKiloBytes
#ifndef fileSizeMegaBytes
#define fileSizeMegaBytes "Mo"
#endif // fileSizeMegaBytes
#ifndef fileSizeGigaBytes
#define fileSizeGigaBytes "Go"
#endif // fileSizeGigaBytes
#ifndef OverWriteDialogTitleString
#define OverWriteDialogTitleString "The selected file already exists!"
#endif // OverWriteDialogTitleString
#ifndef OverWriteDialogMessageString
#define OverWriteDialogMessageString "Are you sure you want to overwrite it?"
#endif // OverWriteDialogMessageString
#ifndef OverWriteDialogConfirmButtonString
#define OverWriteDialogConfirmButtonString "Confirm"
#endif // OverWriteDialogConfirmButtonString
#ifndef OverWriteDialogCancelButtonString
#define OverWriteDialogCancelButtonString "Cancel"
#endif // OverWriteDialogCancelButtonString
#ifndef DateTimeFormat
// see strftime functionin <ctime> for customize
#define DateTimeFormat "%Y/%m/%d %H:%M"
#endif // DateTimeFormat
///////////////////////////////
//// SHORTCUTS => ctrl + KEY
///////////////////////////////
#ifndef SelectAllFilesKey
#define SelectAllFilesKey ImGuiKey_A
#endif // SelectAllFilesKey
///////////////////////////////
// THUMBNAILS
///////////////////////////////
#ifdef USE_THUMBNAILS
#ifndef tableHeaderFileThumbnailsString
#define tableHeaderFileThumbnailsString "Thumbnails"
#endif // tableHeaderFileThumbnailsString
#ifndef DisplayMode_FilesList_ButtonString
#define DisplayMode_FilesList_ButtonString "FL"
#endif // DisplayMode_FilesList_ButtonString
#ifndef DisplayMode_FilesList_ButtonHelp
#define DisplayMode_FilesList_ButtonHelp "File List"
#endif // DisplayMode_FilesList_ButtonHelp
#ifndef DisplayMode_ThumbailsList_ButtonString
#define DisplayMode_ThumbailsList_ButtonString "TL"
#endif // DisplayMode_ThumbailsList_ButtonString
#ifndef DisplayMode_ThumbailsList_ButtonHelp
#define DisplayMode_ThumbailsList_ButtonHelp "Thumbnails List"
#endif // DisplayMode_ThumbailsList_ButtonHelp
#ifndef DisplayMode_ThumbailsGrid_ButtonString
#define DisplayMode_ThumbailsGrid_ButtonString "TG"
#endif // DisplayMode_ThumbailsGrid_ButtonString
#ifndef DisplayMode_ThumbailsGrid_ButtonHelp
#define DisplayMode_ThumbailsGrid_ButtonHelp "Thumbnails Grid"
#endif // DisplayMode_ThumbailsGrid_ButtonHelp
#ifndef DisplayMode_ThumbailsList_ImageHeight
#define DisplayMode_ThumbailsList_ImageHeight 32.0f
#endif // DisplayMode_ThumbailsList_ImageHeight
#ifndef IMGUI_RADIO_BUTTON
inline bool inRadioButton(const char* vLabel, bool vToggled) {
bool pressed = false;
if (vToggled) {
ImVec4 bua = ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive);
ImVec4 te = ImGui::GetStyleColorVec4(ImGuiCol_Text);
ImGui::PushStyleColor(ImGuiCol_Button, te);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, te);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, te);
ImGui::PushStyleColor(ImGuiCol_Text, bua);
}
pressed = IMGUI_BUTTON(vLabel);
if (vToggled) {
ImGui::PopStyleColor(4); //-V112
}
return pressed;
}
#define IMGUI_RADIO_BUTTON inRadioButton
#endif // IMGUI_RADIO_BUTTON
#endif // USE_THUMBNAILS
///////////////////////////////
// PLACES
///////////////////////////////
#ifdef USE_PLACES_FEATURE
#ifndef defaultPlacePaneWith
#define defaultPlacePaneWith 150.0f
#endif // defaultPlacePaneWith
#ifndef placesButtonString
#define placesButtonString "Places"
#endif // placesButtonString
#ifndef placesButtonHelpString
#define placesButtonHelpString "Places"
#endif // placesButtonHelpString
#ifndef placesBookmarksGroupName
#define placesBookmarksGroupName "Bookmarks"
#endif // placesBookmarksGroupName
#ifndef PLACES_BOOKMARK_DEFAULT_OPEPEND
#define PLACES_BOOKMARK_DEFAULT_OPEPEND true
#endif // PLACES_BOOKMARK_DEFAULT_OPEPEND
#ifndef PLACES_DEVICES_DEFAULT_OPEPEND
#define PLACES_DEVICES_DEFAULT_OPEPEND true
#endif // PLACES_DEVICES_DEFAULT_OPEPEND
#ifndef placesBookmarksDisplayOrder
#define placesBookmarksDisplayOrder 0
#endif // placesBookmarksDisplayOrder
#ifndef placesDevicesGroupName
#define placesDevicesGroupName "Devices"
#endif // placesDevicesGroupName
#ifndef placesDevicesDisplayOrder
#define placesDevicesDisplayOrder 10
#endif // placesDevicesDisplayOrder
#ifndef addPlaceButtonString
#define addPlaceButtonString "+"
#endif // addPlaceButtonString
#ifndef removePlaceButtonString
#define removePlaceButtonString "-"
#endif // removePlaceButtonString
#ifndef validatePlaceButtonString
#define validatePlaceButtonString "ok"
#endif // validatePlaceButtonString
#ifndef editPlaceButtonString
#define editPlaceButtonString "E"
#endif // editPlaceButtonString
#ifndef PLACES_PANE_DEFAULT_SHOWN
#define PLACES_PANE_DEFAULT_SHOWN false
#endif // PLACES_PANE_DEFAULT_SHOWN
#ifndef IMGUI_TOGGLE_BUTTON
inline bool inToggleButton(const char* vLabel, bool* vToggled) {
bool pressed = false;
if (vToggled && *vToggled) {
ImVec4 bua = ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive);
// ImVec4 buh = ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered);
// ImVec4 bu = ImGui::GetStyleColorVec4(ImGuiCol_Button);
ImVec4 te = ImGui::GetStyleColorVec4(ImGuiCol_Text);
ImGui::PushStyleColor(ImGuiCol_Button, te);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, te);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, te);
ImGui::PushStyleColor(ImGuiCol_Text, bua);
}
pressed = IMGUI_BUTTON(vLabel);
if (vToggled && *vToggled) {
ImGui::PopStyleColor(4); //-V112
}
if (vToggled && pressed) *vToggled = !*vToggled;
return pressed;
}
#define IMGUI_TOGGLE_BUTTON inToggleButton
#endif // IMGUI_TOGGLE_BUTTON
#endif // USE_PLACES_FEATURE
class IGFDException : public std::exception {
private:
char const* m_msg{};
public:
IGFDException() : std::exception() {
}
explicit IGFDException(char const* const vMsg)
: std::exception(), // std::exception(msg) is not availaiable on linux it seems... but on windos yes
m_msg(vMsg) {
}
char const* what() const noexcept override {
return m_msg;
}
};
#ifndef CUSTOM_FILESYSTEM_INCLUDE
#ifdef USE_STD_FILESYSTEM
static std::filesystem::path stringToPath(const std::string& str) {
#ifdef _IGFD_WIN_
return std::filesystem::path(IGFD::Utils::UTF8Decode(str));
#else
return std::filesystem::path(str);
#endif
}
static std::string pathToString(const std::filesystem::path& path) {
#ifdef _IGFD_WIN_
return IGFD::Utils::UTF8Encode(path.wstring());
#else
return path.string();
#endif
}
class FileSystemStd : public IGFD::IFileSystem {
public:
bool IsDirectoryCanBeOpened(const std::string& vName) override {
bool bExists = false;
if (!vName.empty()) {
namespace fs = std::filesystem;
auto pathName = stringToPath(vName);
try {
// interesting, in the case of a protected dir or for any reason the dir cant be opened
// this func will work but will say nothing more . not like the dirent version
bExists = fs::is_directory(pathName);
// test if can be opened, this function can thrown an exception if there is an issue with this dir
// here, the dir_iter is need else not exception is thrown..
const auto dir_iter = fs::directory_iterator(pathName);
(void)dir_iter; // for avoid unused warnings
} catch (const std::exception& /*ex*/) {
// fail so this dir cant be opened
bExists = false;
}
}
return bExists; // this is not a directory!
}
bool IsDirectoryExist(const std::string& vName) override {
if (!vName.empty()) {
namespace fs = std::filesystem;
return fs::is_directory(stringToPath(vName));
}
return false; // this is not a directory!
}
bool IsFileExist(const std::string& vName) override {
namespace fs = std::filesystem;
return fs::is_regular_file(stringToPath(vName));
}
bool CreateDirectoryIfNotExist(const std::string& vName) override {
if (vName.empty()) return false;
if (IsDirectoryExist(vName)) return true;
#if defined(__EMSCRIPTEN__)
std::string str = std::string("FS.mkdir('") + vName + "');";
emscripten_run_script(str.c_str());
bool res = true;
#else
namespace fs = std::filesystem;
bool res = fs::create_directory(stringToPath(vName));
#endif // _IGFD_WIN_
if (!res) {
std::cout << "Error creating directory " << vName << std::endl;
}
return res;
}
std::vector<IGFD::PathDisplayedName> GetDevicesList() override {
std::vector<IGFD::PathDisplayedName> res;
#ifdef _IGFD_WIN_
const DWORD mydevices = 2048;
char lpBuffer[2048];
#define mini(a, b) (((a) < (b)) ? (a) : (b))
const DWORD countChars = mini(GetLogicalDriveStringsA(mydevices, lpBuffer), 2047);
#undef mini
if (countChars > 0U && countChars < 2049U) {
std::string var = std::string(lpBuffer, (size_t)countChars);
IGFD::Utils::ReplaceString(var, "\\", "");
auto arr = IGFD::Utils::SplitStringToVector(var, '\0', false);
wchar_t szVolumeName[2048];
IGFD::PathDisplayedName path_name;
for (auto& a : arr) {
path_name.first = a;
path_name.second.clear();
std::wstring wpath = IGFD::Utils::UTF8Decode(a);
if (GetVolumeInformationW(wpath.c_str(), szVolumeName, 2048, nullptr, nullptr, nullptr, nullptr, 0)) {
path_name.second = IGFD::Utils::UTF8Encode(szVolumeName);
}
res.push_back(path_name);
}
}
#endif // _IGFD_WIN_
return res;
}
IGFD::Utils::PathStruct ParsePathFileName(const std::string& vPathFileName) override {
// https://github.com/aiekick/ImGuiFileDialog/issues/54
namespace fs = std::filesystem;
IGFD::Utils::PathStruct res;
if (vPathFileName.empty()) return res;
auto fsPath = stringToPath(vPathFileName);
if (fs::is_directory(fsPath)) {
res.name = "";
res.path = pathToString(fsPath);
res.isOk = true;
} else if (fs::is_regular_file(fsPath)) {
res.name = pathToString(fsPath.filename());
res.path = pathToString(fsPath.parent_path());
res.isOk = true;
}
return res;
}
std::vector<IGFD::FileInfos> ScanDirectory(const std::string& vPath) override {
std::vector<IGFD::FileInfos> res;
try {
namespace fs = std::filesystem;
auto fspath = stringToPath(vPath);
const auto dir_iter = fs::directory_iterator(fspath);
IGFD::FileType fstype = IGFD::FileType(IGFD::FileType::ContentType::Directory, fs::is_symlink(fs::status(fspath)));
{
IGFD::FileInfos file_two_dot;
file_two_dot.filePath = vPath;
file_two_dot.fileNameExt = "..";
file_two_dot.fileType = fstype;
res.push_back(file_two_dot);
}
for (const auto& file : dir_iter) {
try {
IGFD::FileType fileType;
if (file.is_symlink()) {
fileType.SetSymLink(file.is_symlink());
fileType.SetContent(IGFD::FileType::ContentType::LinkToUnknown);
}
if (file.is_directory()) {
fileType.SetContent(IGFD::FileType::ContentType::Directory);
} // directory or symlink to directory
else if (file.is_regular_file()) {
fileType.SetContent(IGFD::FileType::ContentType::File);
}
if (fileType.isValid()) {
auto fileNameExt = pathToString(file.path().filename());
{
IGFD::FileInfos _file;
_file.filePath = vPath;
_file.fileNameExt = fileNameExt;
_file.fileType = fileType;
res.push_back(_file);
}
}
} catch (const std::exception& ex) {
std::cout << "IGFD : " << ex.what() << std::endl;
}
}
} catch (const std::exception& ex) {
std::cout << "IGFD : " << ex.what() << std::endl;
}
return res;
}
bool IsDirectory(const std::string& vFilePathName) override {
namespace fs = std::filesystem;
return fs::is_directory(stringToPath(vFilePathName));
}
};
#define FILE_SYSTEM_OVERRIDE FileSystemStd
#else
class FileSystemDirent : public IGFD::IFileSystem {
public:
bool IsDirectoryCanBeOpened(const std::string& vName) override {
if (!vName.empty()) {
DIR* pDir = nullptr;
// interesting, in the case of a protected dir or for any reason the dir cant be opened
// this func will fail
pDir = opendir(vName.c_str());
if (pDir != nullptr) {
(void)closedir(pDir);
return true;
}
}
return false;
}
bool IsDirectoryExist(const std::string& vName) override {
bool bExists = false;
if (!vName.empty()) {
DIR* pDir = nullptr;
pDir = opendir(vName.c_str());
if (pDir) {
bExists = true;
closedir(pDir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
// bExists = false;
} else {
/* opendir() failed for some other reason.
like if a dir is protected, or not accessable with user right
*/
bExists = true;
}
}
return bExists;
}
bool IsFileExist(const std::string& vName) override {
std::ifstream docFile(vName, std::ios::in);
if (docFile.is_open()) {
docFile.close();
return true;
}
return false;
}
bool CreateDirectoryIfNotExist(const std::string& vName) override {
bool res = false;
if (!vName.empty()) {
if (!IsDirectoryExist(vName)) {
#ifdef _IGFD_WIN_
std::wstring wname = IGFD::Utils::UTF8Decode(vName);
if (CreateDirectoryW(wname.c_str(), nullptr)) {
res = true;
}
#elif defined(__EMSCRIPTEN__) // _IGFD_WIN_
std::string str = std::string("FS.mkdir('") + vName + "');";
emscripten_run_script(str.c_str());
res = true;
#elif defined(_IGFD_UNIX_)
char buffer[PATH_MAX] = {};
snprintf(buffer, PATH_MAX, "mkdir -p \"%s\"", vName.c_str());
const int dir_err = std::system(buffer);
if (dir_err != -1) {
res = true;
}
#endif // _IGFD_WIN_
if (!res) {
std::cout << "Error creating directory " << vName << std::endl;
}
}
}
return res;
}
std::vector<IGFD::PathDisplayedName> GetDevicesList() override {
std::vector<IGFD::PathDisplayedName> res;
#ifdef _IGFD_WIN_
const DWORD mydevices = 2048;
char lpBuffer[2048];
#define mini(a, b) (((a) < (b)) ? (a) : (b))
const DWORD countChars = mini(GetLogicalDriveStringsA(mydevices, lpBuffer), 2047);
#undef mini
if (countChars > 0U && countChars < 2049U) {
std::string var = std::string(lpBuffer, (size_t)countChars);
IGFD::Utils::ReplaceString(var, "\\", "");
auto arr = IGFD::Utils::SplitStringToVector(var, '\0', false);
wchar_t szVolumeName[2048];
IGFD::PathDisplayedName path_name;
for (auto& a : arr) {
path_name.first = a;
path_name.second.clear();
std::wstring wpath = IGFD::Utils::UTF8Decode(a);
if (GetVolumeInformationW(wpath.c_str(), szVolumeName, 2048, nullptr, nullptr, nullptr, nullptr, 0)) {
path_name.second = IGFD::Utils::UTF8Encode(szVolumeName);
}
res.push_back(path_name);
}
}
#endif // _IGFD_WIN_
return res;
}
IGFD::Utils::PathStruct ParsePathFileName(const std::string& vPathFileName) override {
IGFD::Utils::PathStruct res;
if (!vPathFileName.empty()) {
std::string pfn = vPathFileName;
std::string separator(1u, PATH_SEP);
IGFD::Utils::ReplaceString(pfn, "\\", separator);
IGFD::Utils::ReplaceString(pfn, "/", separator);
size_t lastSlash = pfn.find_last_of(separator);
if (lastSlash != std::string::npos) {
res.name = pfn.substr(lastSlash + 1);
res.path = pfn.substr(0, lastSlash);
res.isOk = true;
}
size_t lastPoint = pfn.find_last_of('.');
if (lastPoint != std::string::npos) {
if (!res.isOk) {
res.name = pfn;
res.isOk = true;
}
res.ext = pfn.substr(lastPoint + 1);
IGFD::Utils::ReplaceString(res.name, "." + res.ext, "");
}
if (!res.isOk) {
res.name = std::move(pfn);
res.isOk = true;
}
}
return res;
}
std::vector<IGFD::FileInfos> ScanDirectory(const std::string& vPath) override {
std::vector<IGFD::FileInfos> res;
struct dirent** files = nullptr;
size_t n = scandir(vPath.c_str(), &files, nullptr, //
[](const struct dirent** a, const struct dirent** b) { //
return strcoll((*a)->d_name, (*b)->d_name);
});
if (n && files) {
for (size_t i = 0; i < n; ++i) {
struct dirent* ent = files[i];
IGFD::FileType fileType;
switch (ent->d_type) {
case DT_DIR: fileType.SetContent(IGFD::FileType::ContentType::Directory); break;
case DT_REG: fileType.SetContent(IGFD::FileType::ContentType::File); break;
#if defined(_IGFD_UNIX_) || (DT_LNK != DT_UNKNOWN)
case DT_LNK:
#endif
case DT_UNKNOWN: {
struct stat sb = {};
#ifdef _IGFD_WIN_
auto filePath = vPath + ent->d_name;
#else
auto filePath = vPath + IGFD::Utils::GetPathSeparator() + ent->d_name;
#endif
if (!stat(filePath.c_str(), &sb)) {
if (sb.st_mode & S_IFLNK) {
fileType.SetSymLink(true);
// by default if we can't figure out the target type.
fileType.SetContent(IGFD::FileType::ContentType::LinkToUnknown);
}
if (sb.st_mode & S_IFREG) {
fileType.SetContent(IGFD::FileType::ContentType::File);
break;
} else if (sb.st_mode & S_IFDIR) {
fileType.SetContent(IGFD::FileType::ContentType::Directory);
break;
}
}
break;
}
default: break; // leave it invalid (devices, etc.)
}
if (fileType.isValid()) {
IGFD::FileInfos _file;
_file.filePath = vPath;
_file.fileNameExt = ent->d_name;
_file.fileType = fileType;
res.push_back(_file);
}
}
for (size_t i = 0; i < n; ++i) {
free(files[i]);
}
free(files);
}
return res;
}
bool IsDirectory(const std::string& vFilePathName) override {
DIR* pDir = opendir(vFilePathName.c_str());
if (pDir) {
(void)closedir(pDir);
return true;
}
return false;
}
};
#define FILE_SYSTEM_OVERRIDE FileSystemDirent
#endif // USE_STD_FILESYSTEM
#else
#include CUSTOM_FILESYSTEM_INCLUDE
#endif // USE_CUSTOM_FILESYSTEM
// https://github.com/ocornut/imgui/issues/1720
bool IGFD::Utils::ImSplitter(bool split_vertically, float thickness, float* size1, float* size2, float min_size1, float min_size2, float splitter_long_axis_size) {
auto* window = ImGui::GetCurrentWindow();
ImGuiID id = window->GetID("##Splitter");
ImRect bb;
bb.Min = window->DC.CursorPos + (split_vertically ? ImVec2(*size1, 0.0f) : ImVec2(0.0f, *size1));
bb.Max = bb.Min + ImGui::CalcItemSize(split_vertically ? ImVec2(thickness, splitter_long_axis_size) : ImVec2(splitter_long_axis_size, thickness), 0.0f, 0.0f);
return ImGui::SplitterBehavior(bb, id, split_vertically ? ImGuiAxis_X : ImGuiAxis_Y, size1, size2, min_size1, min_size2, 1.0f, 0.0, ImGui::GetColorU32(ImGuiCol_FrameBg));
}
// Convert a wide Unicode string to an UTF8 string
std::string IGFD::Utils::UTF8Encode(const std::wstring& wstr) {
std::string res;
#ifdef _IGFD_WIN_
if (!wstr.empty()) {
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), nullptr, 0, nullptr, nullptr);
if (size_needed) {
res = std::string(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &res[0], size_needed, nullptr, nullptr);
}
}
#else
// Suppress warnings from the compiler.
(void)wstr;
#endif // _IGFD_WIN_
return res;
}
// Convert an UTF8 string to a wide Unicode String
std::wstring IGFD::Utils::UTF8Decode(const std::string& str) {
std::wstring res;
#ifdef _IGFD_WIN_
if (!str.empty()) {
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), nullptr, 0);
if (size_needed) {
res = std::wstring(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &res[0], size_needed);
}
}
#else
// Suppress warnings from the compiler.
(void)str;
#endif // _IGFD_WIN_
return res;
}
bool IGFD::Utils::ReplaceString(std::string& str, const ::std::string& oldStr, const ::std::string& newStr, const size_t& vMaxRecursion) {
if (!str.empty() && oldStr != newStr) {
bool res = false;
size_t pos = 0;
bool found = false;
size_t max_recursion = vMaxRecursion;
do {
pos = str.find(oldStr, pos);
if (pos != std::string::npos) {
found = res = true;
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
} else if (found && max_recursion > 0) { // recursion loop
found = false;
pos = 0;
--max_recursion;
}
} while (pos != std::string::npos);
return res;
}
return false;
}
std::vector<std::string> IGFD::Utils::SplitStringToVector(const std::string& vText, const std::string& vDelimiterPattern, const bool& vPushEmpty) {
std::vector<std::string> arr;
if (!vText.empty()) {
size_t start = 0;
size_t end = vText.find(vDelimiterPattern, start);
while (end != std::string::npos) {
auto token = vText.substr(start, end - start);
if (!token.empty() || (token.empty() && vPushEmpty)) { //-V728
arr.push_back(token);
}
start = end + vDelimiterPattern.size();
end = vText.find(vDelimiterPattern, start);
}
auto token = vText.substr(start);
if (!token.empty() || (token.empty() && vPushEmpty)) { //-V728
arr.push_back(token);
}
}
return arr;
}
std::vector<std::string> IGFD::Utils::SplitStringToVector(const std::string& vText, const char& vDelimiter, const bool& vPushEmpty) {
std::vector<std::string> arr;
if (!vText.empty()) {
size_t start = 0;
size_t end = vText.find(vDelimiter, start);
while (end != std::string::npos) {
auto token = vText.substr(start, end - start);
if (!token.empty() || (token.empty() && vPushEmpty)) { //-V728
arr.push_back(token);
}
start = end + 1;
end = vText.find(vDelimiter, start);
}
auto token = vText.substr(start);
if (!token.empty() || (token.empty() && vPushEmpty)) { //-V728
arr.push_back(token);
}
}
return arr;
}
void IGFD::Utils::AppendToBuffer(char* vBuffer, size_t vBufferLen, const std::string& vStr) {
std::string st = vStr;
size_t len = vBufferLen - 1u;
size_t slen = strlen(vBuffer);
if (!st.empty() && st != "\n") {
IGFD::Utils::ReplaceString(st, "\n", "");
IGFD::Utils::ReplaceString(st, "\r", "");
}
vBuffer[slen] = '\0';
std::string str = std::string(vBuffer);
// if (!str.empty()) str += "\n";
str += vStr;
if (len > str.size()) {
len = str.size();
}
#ifdef _MSC_VER
strncpy_s(vBuffer, vBufferLen, str.c_str(), len);
#else // _MSC_VER
strncpy(vBuffer, str.c_str(), len);
#endif // _MSC_VER
vBuffer[len] = '\0';
}
void IGFD::Utils::ResetBuffer(char* vBuffer) {
vBuffer[0] = '\0';
}
void IGFD::Utils::SetBuffer(char* vBuffer, size_t vBufferLen, const std::string& vStr) {
ResetBuffer(vBuffer);
AppendToBuffer(vBuffer, vBufferLen, vStr);
}
std::string IGFD::Utils::LowerCaseString(const std::string& vString) {
auto str = vString;
// convert to lower case
for (char& c : str) {
c = (char)std::tolower(c);
}
return str;
}
size_t IGFD::Utils::GetCharCountInString(const std::string& vString, const char& vChar) {
size_t res = 0U;
for (const auto& c : vString) {
if (c == vChar) {
++res;
}
}
return res;
}
size_t IGFD::Utils::GetLastCharPosWithMinCharCount(const std::string& vString, const char& vChar, const size_t& vMinCharCount) {
if (vMinCharCount) {
size_t last_dot_pos = vString.size() + 1U;
size_t count_dots = vMinCharCount;
while (count_dots > 0U && last_dot_pos > 0U && last_dot_pos != std::string::npos) {
auto new_dot = vString.rfind(vChar, last_dot_pos - 1U);
if (new_dot != std::string::npos) {
last_dot_pos = new_dot;
--count_dots;
} else {
break;
}
}
return last_dot_pos;
}
return std::string::npos;
}
std::string IGFD::Utils::GetPathSeparator() {
return std::string(1U, PATH_SEP);
}
std::string IGFD::Utils::RoundNumber(double vvalue, int n) {
std::stringstream tmp;
tmp << std::setprecision(n) << std::fixed << vvalue;
return tmp.str();
}
std::string IGFD::Utils::FormatFileSize(size_t vByteSize) {
if (vByteSize != 0) {
static double lo = 1024.0;
static double ko = 1024.0 * 1024.0;
static double mo = 1024.0 * 1024.0 * 1024.0;
const auto v = static_cast<double>(vByteSize);
if (v < lo)
return RoundNumber(v, 0) + " " + fileSizeBytes; // octet
else if (v < ko)
return RoundNumber(v / lo, 2) + " " + fileSizeKiloBytes; // ko
else if (v < mo)
return RoundNumber(v / ko, 2) + " " + fileSizeMegaBytes; // Mo
else
return RoundNumber(v / mo, 2) + " " + fileSizeGigaBytes; // Go