forked from aiekick/ImGuiFileDialog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImGuiFileDialog.cpp
4946 lines (4241 loc) · 192 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
#pragma region PVS STUDIO
// 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
#pragma endregion
#pragma region IGFD LICENSE
/*
MIT License
Copyright (c) 2019-2020 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.
*/
#pragma endregion
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "ImGuiFileDialog.h"
#ifdef __cplusplus
#pragma region Includes
#include <cfloat>
#include <cstring> // stricmp / strcasecmp
#include <cstdarg> // variadic
#include <sstream>
#include <iomanip>
#include <ctime>
#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 _stat
#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(__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"
#include <cstdlib>
#include <algorithm>
#include <iostream>
#pragma endregion
#pragma region Common defines
#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_resize.h"
#endif // USE_THUMBNAILS
// 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
#pragma endregion
#pragma region IGFD NAMESPACE
#pragma region CUSTOMIZATION DEFINES
///////////////////////////////
// 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 drivesButtonString
#define drivesButtonString "Drives"
#endif // drivesButtonString
#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 "Drives"
#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 file Already Exist !"
#endif // OverWriteDialogTitleString
#ifndef OverWriteDialogMessageString
#define OverWriteDialogMessageString "Would you like 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
///////////////////////////////
// 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
///////////////////////////////
// BOOKMARKS
///////////////////////////////
#ifdef USE_BOOKMARK
#ifndef defaultBookmarkPaneWith
#define defaultBookmarkPaneWith 150.0f
#endif // defaultBookmarkPaneWith
#ifndef bookmarksButtonString
#define bookmarksButtonString "Bookmark"
#endif // bookmarksButtonString
#ifndef bookmarksButtonHelpString
#define bookmarksButtonHelpString "Bookmark"
#endif // bookmarksButtonHelpString
#ifndef addBookmarkButtonString
#define addBookmarkButtonString "+"
#endif // addBookmarkButtonString
#ifndef removeBookmarkButtonString
#define removeBookmarkButtonString "-"
#endif // removeBookmarkButtonString
#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_BOOKMARK
#pragma endregion
#pragma region INTERNAL
#pragma region EXCEPTION
class IGFDException : public std::exception {
private:
std::string m_Message;
public:
IGFDException(const std::string& vMessage) : m_Message(vMessage) {
}
const char* what() {
return m_Message.c_str();
}
};
#pragma endregion
#pragma region Utils
#ifndef USE_STD_FILESYSTEM
inline int inAlphaSort(const struct dirent** a, const struct dirent** b) {
return strcoll((*a)->d_name, (*b)->d_name);
}
#endif
// https://github.com/ocornut/imgui/issues/1720
IGFD_API bool IGFD::Utils::ImSplitter(bool split_vertically, float thickness, float* size1, float* size2, float min_size1, float min_size2, float splitter_long_axis_size) {
using namespace ImGui;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
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 + CalcItemSize(split_vertically ? ImVec2(thickness, splitter_long_axis_size) : ImVec2(splitter_long_axis_size, thickness), 0.0f, 0.0f);
return SplitterBehavior(bb, id, split_vertically ? ImGuiAxis_X : ImGuiAxis_Y, size1, size2, min_size1, min_size2, 1.0f);
}
IGFD_API bool IGFD::Utils::WReplaceString(std::wstring& str, const std::wstring& oldStr, const std::wstring& newStr) {
bool found = false;
#ifdef _IGFD_WIN_
size_t pos = 0;
while ((pos = str.find(oldStr, pos)) != std::wstring::npos) {
found = true;
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
#else
// Suppress warnings from the compiler.
(void)str;
(void)oldStr;
(void)newStr;
#endif // _IGFD_WIN_
return found;
}
IGFD_API std::vector<std::wstring> IGFD::Utils::WSplitStringToVector(const std::wstring& text, char delimiter, bool pushEmpty) {
std::vector<std::wstring> arr;
#ifdef _IGFD_WIN_
if (!text.empty()) {
std::wstring::size_type start = 0;
std::wstring::size_type end = text.find(delimiter, start);
while (end != std::wstring::npos) {
std::wstring token = text.substr(start, end - start);
if (!token.empty() || (token.empty() && pushEmpty)) { //-V728
arr.push_back(token);
}
start = end + 1;
end = text.find(delimiter, start);
}
std::wstring token = text.substr(start);
if (!token.empty() || (token.empty() && pushEmpty)) { //-V728
arr.push_back(token);
}
}
#else
// Suppress warnings from the compiler.
(void)text;
(void)delimiter;
(void)pushEmpty;
#endif // _IGFD_WIN_
return arr;
}
// Convert a wide Unicode string to an UTF8 string
IGFD_API std::string IGFD::Utils::utf8_encode(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(), NULL, 0, NULL, NULL);
if (size_needed) {
res = std::string(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &res[0], size_needed, NULL, NULL);
}
}
#else
// Suppress warnings from the compiler.
(void)wstr;
#endif // _IGFD_WIN_
return res;
}
// Convert an UTF8 string to a wide Unicode String
IGFD_API std::wstring IGFD::Utils::utf8_decode(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(), NULL, 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;
}
IGFD_API bool IGFD::Utils::ReplaceString(std::string& str, const std::string& oldStr, const std::string& newStr) {
bool res = false;
size_t pos = 0;
bool found = false;
do {
pos = str.find(oldStr, pos);
if (pos != std::string::npos) {
found = true;
res = true;
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
} else if (found) { // another loop to be sure there is no other pattern ater replacement
found = false;
pos = 0;
}
} while (pos != std::string::npos);
return res;
}
IGFD_API std::vector<std::string> IGFD::Utils::SplitStringToVector(const std::string& text, char delimiter, bool pushEmpty) {
std::vector<std::string> arr;
if (!text.empty()) {
size_t start = 0;
size_t end = text.find(delimiter, start);
while (end != std::string::npos) {
auto token = text.substr(start, end - start);
if (!token.empty() || (token.empty() && pushEmpty)) { //-V728
arr.push_back(token);
}
start = end + 1;
end = text.find(delimiter, start);
}
auto token = text.substr(start);
if (!token.empty() || (token.empty() && pushEmpty)) { //-V728
arr.push_back(token);
}
}
return arr;
}
IGFD_API std::vector<std::string> IGFD::Utils::GetDrivesList() {
std::vector<std::string> res;
#ifdef _IGFD_WIN_
const DWORD mydrives = 2048;
char lpBuffer[2048];
#define mini(a, b) (((a) < (b)) ? (a) : (b))
const DWORD countChars = mini(GetLogicalDriveStringsA(mydrives, lpBuffer), 2047);
#undef mini
if (countChars > 0U && countChars < 2049U) {
std::string var = std::string(lpBuffer, (size_t)countChars);
IGFD::Utils::ReplaceString(var, "\\", "");
res = IGFD::Utils::SplitStringToVector(var, '\0', false);
}
#endif // _IGFD_WIN_
return res;
}
IGFD_API bool IGFD::Utils::IsDirectoryCanBeOpened(const std::string& name) {
bool bExists = false;
if (!name.empty()) {
#ifdef USE_STD_FILESYSTEM
namespace fs = std::filesystem;
#ifdef _IGFD_WIN_
std::wstring wname = IGFD::Utils::utf8_decode(name.c_str());
fs::path pathName = fs::path(wname);
#else // _IGFD_WIN_
fs::path pathName = fs::path(name);
#endif // _IGFD_WIN_
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 = std::filesystem::directory_iterator(pathName);
(void)dir_iter; // for avoid unused warnings
} catch (const std::exception& /*ex*/) {
// fail so this dir cant be opened
bExists = false;
}
#else
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(name.c_str());
if (pDir != nullptr) {
bExists = true;
(void)closedir(pDir);
}
#endif // USE_STD_FILESYSTEM
}
return bExists; // this is not a directory!
}
IGFD_API bool IGFD::Utils::IsDirectoryExist(const std::string& name) {
bool bExists = false;
if (!name.empty()) {
#ifdef USE_STD_FILESYSTEM
namespace fs = std::filesystem;
#ifdef _IGFD_WIN_
std::wstring wname = IGFD::Utils::utf8_decode(name.c_str());
fs::path pathName = fs::path(wname);
#else // _IGFD_WIN_
fs::path pathName = fs::path(name);
#endif // _IGFD_WIN_
bExists = fs::is_directory(pathName);
#else
DIR* pDir = nullptr;
pDir = opendir(name.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;
}
#endif // USE_STD_FILESYSTEM
}
return bExists; // this is not a directory!
}
IGFD_API bool IGFD::Utils::CreateDirectoryIfNotExist(const std::string& name) {
bool res = false;
if (!name.empty()) {
if (!IsDirectoryExist(name)) {
#ifdef _IGFD_WIN_
#ifdef USE_STD_FILESYSTEM
namespace fs = std::filesystem;
std::wstring wname = IGFD::Utils::utf8_decode(name.c_str());
fs::path pathName = fs::path(wname);
res = fs::create_directory(pathName);
#else // USE_STD_FILESYSTEM
std::wstring wname = IGFD::Utils::utf8_decode(name);
if (CreateDirectoryW(wname.c_str(), nullptr)) {
res = true;
}
#endif // USE_STD_FILESYSTEM
#elif defined(__EMSCRIPTEN__) // _IGFD_WIN_
std::string str = std::string("FS.mkdir('") + name + "');";
emscripten_run_script(str.c_str());
res = true;
#elif defined(_IGFD_UNIX_)
char buffer[PATH_MAX] = {};
snprintf(buffer, PATH_MAX, "mkdir -p \"%s\"", name.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 " << name << std::endl;
}
}
}
return res;
}
IGFD_API IGFD::Utils::PathStruct IGFD::Utils::ParsePathFileName(const std::string& vPathFileName) {
#ifdef USE_STD_FILESYSTEM
// https://github.com/aiekick/ImGuiFileDialog/issues/54
namespace fs = std::filesystem;
PathStruct res;
if (vPathFileName.empty()) return res;
auto fsPath = fs::path(vPathFileName);
if (fs::is_directory(fsPath)) {
res.name = "";
res.path = fsPath.string();
res.isOk = true;
} else if (fs::is_regular_file(fsPath)) {
res.name = fsPath.filename().string();
res.path = fsPath.parent_path().string();
res.isOk = true;
}
return res;
#else
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;
#endif // USE_STD_FILESYSTEM
}
IGFD_API 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';
}
IGFD_API void IGFD::Utils::ResetBuffer(char* vBuffer) {
vBuffer[0] = '\0';
}
IGFD_API void IGFD::Utils::SetBuffer(char* vBuffer, size_t vBufferLen, const std::string& vStr) {
ResetBuffer(vBuffer);
AppendToBuffer(vBuffer, vBufferLen, vStr);
}
IGFD_API 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;
}
IGFD_API 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;
}
IGFD_API 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;
}
#pragma endregion
#pragma region FileStyle
IGFD_API IGFD::FileStyle::FileStyle() : color(0, 0, 0, 0) {
}
IGFD_API IGFD::FileStyle::FileStyle(const FileStyle& vStyle) {
color = vStyle.color;
icon = vStyle.icon;
font = vStyle.font;
flags = vStyle.flags;
}
IGFD_API IGFD::FileStyle::FileStyle(const ImVec4& vColor, const std::string& vIcon, ImFont* vFont) : color(vColor), icon(vIcon), font(vFont) {
}
#pragma endregion
#pragma region SearchManager
IGFD_API void IGFD::SearchManager::Clear() {
puSearchTag.clear();
IGFD::Utils::ResetBuffer(puSearchBuffer);
}
IGFD_API void IGFD::SearchManager::DrawSearchBar(FileDialogInternal& vFileDialogInternal) {
// search field
if (IMGUI_BUTTON(resetButtonString "##BtnImGuiFileDialogSearchField")) {
Clear();
vFileDialogInternal.puFileManager.ApplyFilteringOnFileList(vFileDialogInternal);
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip(buttonResetSearchString);
ImGui::SameLine();
ImGui::Text(searchString);
ImGui::SameLine();
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
bool edited = ImGui::InputText("##InputImGuiFileDialogSearchField", puSearchBuffer, MAX_FILE_DIALOG_NAME_BUFFER);
if (ImGui::GetItemID() == ImGui::GetActiveID()) puSearchInputIsActive = true;
ImGui::PopItemWidth();
if (edited) {
puSearchTag = puSearchBuffer;
vFileDialogInternal.puFileManager.ApplyFilteringOnFileList(vFileDialogInternal);
}
}
#pragma endregion
#pragma region FilterInfos
void IGFD::FilterInfos::setCollectionTitle(const std::string& vTitle) {
title = vTitle;
}
void IGFD::FilterInfos::addFilter(const std::string& vFilter, const bool& vIsRegex) {
setCollectionTitle(vFilter);
addCollectionFilter(vFilter, vIsRegex);
}
void IGFD::FilterInfos::addCollectionFilter(const std::string& vFilter, const bool& vIsRegex) {
if (!vIsRegex) {
if (vFilter.find('*') != std::string::npos) {
const auto& regex_string = transformAsteriskBasedFilterToRegex(vFilter);
addCollectionFilter(regex_string, true);
return;
}
filters.try_add(vFilter);
filters_optimized.try_add(Utils::LowerCaseString(vFilter));
auto _count_dots = Utils::GetCharCountInString(vFilter, '.');
if (_count_dots > count_dots) {
count_dots = _count_dots;
}
} else {
try {
auto rx = std::regex(vFilter);
filters.try_add(vFilter);
filters_regex.emplace_back(rx);
} catch (std::exception&) {
assert(0); // YOUR REGEX FILTER IS INVALID
}
}
}
void IGFD::FilterInfos::clear() {
title.clear();
filters.clear();
filters_optimized.clear();
filters_regex.clear();
}
bool IGFD::FilterInfos::empty() const {
return filters.empty() || filters.begin()->empty();
}
const std::string& IGFD::FilterInfos::getFirstFilter() const {
if (!filters.empty()) {
return *filters.begin();
}
return empty_string;
}
bool IGFD::FilterInfos::exist(const FileInfos& vFileInfos, bool vIsCaseInsensitive) const {
for (const auto& filter : filters) {
if (vFileInfos.SearchForExt(filter, vIsCaseInsensitive, count_dots)) {
return true;
}
}
return false;
}
bool IGFD::FilterInfos::regexExist(const std::string& vFilter) const {
for (auto regex : filters_regex) {
if (std::regex_search(vFilter, regex)) {
return true;
}
}
return false;
}
IGFD_API std::string IGFD::FilterInfos::transformAsteriskBasedFilterToRegex(const std::string& vFilter) {
std::string res;
if (!vFilter.empty() && vFilter.find('*') != std::string::npos) {
res = "((";
for (const auto& c : vFilter) {
if (c == '.') {
res += "[.]"; // [.] => a dot
} else if (c == '*') {
res += ".*"; // .* => any char zero or many
} else {
res += c; // other chars
}
}
res += "$))"; // $ => end fo the string
}
return res;
}
#pragma endregion
#pragma region FilterManager
IGFD_API const IGFD::FilterInfos& IGFD::FilterManager::GetSelectedFilter() const {
return prSelectedFilter;
}
IGFD_API void IGFD::FilterManager::ParseFilters(const char* vFilters) {
prParsedFilters.clear();
if (vFilters) {
puDLGFilters = vFilters; // file mode
} else {
puDLGFilters.clear(); // directory mode
}
if (!puDLGFilters.empty()) {
/* Rules
0) a filter must have 2 chars mini and the first must be a .
1) a regex must be in (( and ))
2) a , will separate filters except if between a ( and )
3) name{filter1, filter2} is a spetial form for collection filters
3.1) the name can be composed of what you want except { and }
3.2) the filter can be a regex
4) the filters cannot integrate these chars '(' ')' '{' '}' ' ' except for a regex with respect to rule 1)
5) the filters cannot integrate a ','
*/
bool current_filter_found = false;
bool started = false;
bool regex_started = false;
bool parenthesis_started = false;
std::string word;
std::string filter_name;
char last_split_char = 0;
for (char c : puDLGFilters) {
if (c == '{') {
if (regex_started) {
word += c;
} else {
started = true;
prParsedFilters.emplace_back();
prParsedFilters.back().setCollectionTitle(filter_name);
filter_name.clear();
word.clear();
}
last_split_char = c;
} else if (c == '}') {
if (regex_started) {
word += c;
} else {
if (started) {
if (word.size() > 1U && word[0] == '.') {
if (prParsedFilters.empty()) {
prParsedFilters.emplace_back();
}
prParsedFilters.back().addCollectionFilter(word, false);
}
word.clear();
filter_name.clear();
started = false;
}
}
last_split_char = c;
} else if (c == '(') {
word += c;
if (last_split_char == '(') {
regex_started = true;