-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.cpp
1067 lines (896 loc) · 27.1 KB
/
file.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 <iostream>
#include "filex"
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
#include <sys/utime.h>
#define NOMINMAX
#include <Windows.h>
#include <cstdlib>
#define STRICT_TYPED_ITEMIDS
#include <Shobjidl.h>
#include <Shlobj.h>
#include <locale>
#include <codecvt>
#pragma comment(linker, "\"/manifestdependency:type='Win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#include <libgen.h> // basname / dirname
#include <utime.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <dlfcn.h> // dlopen ...
#endif
namespace stdx
{
long long file_time(char const* name)
{
struct stat buf = { 0 };
stat(name, &buf);
return static_cast<long long>(buf.st_mtime);
}
bool file_touch(char const* name)
{
return utime(name, nullptr) == 0;
}
std::string current_directory()
{
return realpath(".");
}
void current_directory(char const* dir)
{
#ifdef WIN32
SetCurrentDirectoryA(dir);
#else
chdir(dir);
#endif
}
std::string exe_directory()
{
#ifdef WIN32
char path[MAX_PATH];
GetModuleFileNameA(NULL, path, MAX_PATH);
return stdx::dirname(path);
#else
return stdx::dirname(realpath("/proc/self/exe").c_str());
#endif
}
namespace detail
{
namespace relative_path
{
inline bool is_separator(char c) { return c == '\\' || c == '/'; }
inline bool is_separator_or_null(char c) { return c == 0 || is_separator(c); }
size_t const backout_size = 3;
inline char* append_backout(char* cursor) { *cursor++ = '.'; *cursor++ = '.'; *cursor++ = '\\'; return cursor; }
size_t const separator_size = 1;
inline char* append_separator(char* cursor) { *cursor++ = '\\'; return cursor; }
stdx::range<char const*> next_dir(char const* cursor)
{
while (is_separator(*cursor)) ++cursor;
stdx::range<char const*> r(cursor, cursor);
while (!is_separator_or_null(*r.last)) ++r.last;
return r;
}
}
}
std::string dirname(char const* path)
{
#ifdef WIN32
auto lastSeparator = path;
for (auto it = path; *it; ++it)
if (detail::relative_path::is_separator(*it))
lastSeparator = it;
return std::string(path, lastSeparator);
#else
std::string r(path);
auto n = ::dirname(&r[0]);
assert (n == &r[0]);
if (n != &r[0]) strcpy(&r[0], n);
r.resize(strlen(r.c_str()));
return r;
#endif
}
std::string basename(char const* path)
{
#ifdef WIN32
auto lastSeparator = path;
for (auto it = path; *it; ++it)
if (detail::relative_path::is_separator(*it))
lastSeparator = it;
return std::string(lastSeparator + 1);
#else
std::string r(path);
auto n = ::basename(&r[0]);
assert (n == &r[0]);
if (n != &r[0]) strcpy(&r[0], n);
r.resize(strlen(r.c_str()));
return r;
#endif
}
std::string realpath(char const* path)
{
struct default_free { void operator ()(void* p) const { free(p); } };
std::unique_ptr<char, default_free> absolutePath(
#ifdef WIN32
_fullpath(nullptr, path, 0)
#else
::realpath(path, nullptr)
#endif
);
return absolutePath.get();
}
std::string concat_path(char const* tail, char const* head)
{
using namespace detail::relative_path;
auto tailEnd = tail + strlen(tail);
bool addSeparator = (tail != tailEnd && !is_separator(tailEnd[-1]));
std::string concat;
concat.resize(tailEnd - tail + addSeparator + strlen(head));
auto concatCursor = &concat[0];
strcpy(concatCursor, tail);
concatCursor += tailEnd - tail;
if (addSeparator) concatCursor = append_separator(concatCursor);
strcpy(concatCursor, head);
return concat;
}
std::string filesys_relative_path(char const* from, char const* to)
{
return relative_path(realpath(from).c_str(), realpath(to).c_str());
}
std::string relative_path(char const* from, char const* to)
{
using namespace detail::relative_path;
auto fromCursor = from, toCursor = to;
while (true)
{
auto fromDir = next_dir(fromCursor);
auto toDir = next_dir(toCursor);
if (!fromDir.empty() && fromDir.size() == toDir.size() && strncmp(fromDir.first, toDir.first, fromDir.size()) == 0)
{
fromCursor = fromDir.last;
toCursor = toDir.last;
continue;
}
break;
}
size_t numBackout = 0;
while (true)
{
auto fromDir = next_dir(fromCursor);
if (!fromDir.empty())
{
++numBackout;
fromCursor = fromDir.last;
continue;
}
break;
}
while (is_separator(*toCursor)) ++toCursor;
std::string relative;
relative.resize(numBackout * backout_size + strlen(toCursor));
auto relativeCursor = &relative[0];
for (size_t i = 0; i < numBackout; ++i)
relativeCursor = append_backout(relativeCursor);
strcpy(relativeCursor, toCursor);
return relative;
}
std::string load_file(char const* name)
{
std::string str;
auto t = read_file(name);
t.seekg(0, std::ios::end);
str.reserve((size_t) t.tellg());
t.seekg(0, std::ios::beg);
str.assign(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());
return str;
}
std::vector<char> load_binary_file(char const* name, bool nullterminated)
{
std::vector<char> data;
auto t = read_binary_file(name);
t.seekg(0, std::ios::end);
size_t fileSize = (size_t) t.tellg();
data.resize(fileSize + (size_t) nullterminated);
t.seekg(0, std::ios::beg);
t.read(data.data(), fileSize);
return data;
}
module_symbol get_symbol(void* module, char const* name)
{
#ifdef WIN32
return (void(WINAPI*)()) ::GetProcAddress((HMODULE)module, name);
#else
return ::dlsym(module, name);
#endif
}
module::module(char const* name)
{
#ifdef WIN32
handle = ::LoadLibraryA(name);
#else
handle = ::dlopen(name, RTLD_LAZY | RTLD_LOCAL);
#endif
if (!handle)
throwx(std::runtime_error(name));
}
module::~module()
{
#ifdef WIN32
::FreeLibrary((HMODULE)handle);
#else
::dlclose(handle);
#endif
}
#ifdef WIN32
namespace detail
{
namespace generic_file
{
inline DWORD get_windows_access_flags(unsigned access)
{
DWORD winAccess = 0;
if (access & file_flags::read) winAccess |= GENERIC_READ;
if (access & file_flags::write) winAccess |= GENERIC_WRITE;
// Always require some kind of access
if (!winAccess) winAccess = GENERIC_READ;
return winAccess;
}
inline DWORD get_windows_sharing_flags(unsigned share, unsigned access)
{
DWORD winShare = 0;
if (share & file_flags::read) winShare |= FILE_SHARE_READ;
if (share & file_flags::write) winShare |= FILE_SHARE_WRITE;
return winShare;
}
inline DWORD get_windows_open_mode(file_flags::open_mode mode, unsigned access)
{
if (access & file_flags::write)
switch (mode)
{
case file_flags::nonexisting: return CREATE_NEW;
case file_flags::existing: return OPEN_EXISTING;
case file_flags::new_overwrite: return CREATE_ALWAYS;
default: case file_flags::open_or_new: return OPEN_ALWAYS;
}
else
return OPEN_EXISTING;
}
inline DWORD get_windows_optimization_flags(unsigned hints)
{
if (hints & file_flags::sequential) return FILE_FLAG_SEQUENTIAL_SCAN;
else if (hints & file_flags::random) return FILE_FLAG_RANDOM_ACCESS;
else return 0;
}
typedef BOOL (WINAPI* PrefetchVirtualMemoryPtr)(HANDLE hProcess, ULONG_PTR NumberOfEntries, PWIN32_MEMORY_RANGE_ENTRY VirtualAddresses, ULONG Flags);
inline PrefetchVirtualMemoryPtr get_prefetch_function()
{
DWORD dwVersion = GetVersion();
DWORD dwMajor = LOBYTE(LOWORD(dwVersion));
DWORD dwMinor = HIBYTE(LOWORD(dwVersion));
// supported from Win 8 onwards
return (dwMajor >= 6 && dwMinor >= 2)
? (PrefetchVirtualMemoryPtr) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory")
: nullptr;
}
template <class Pointer, BOOL (WINAPI* Deleter)(Pointer)>
struct win_delete
{
typedef Pointer pointer;
void operator ()(pointer ptr) const {
(*Deleter)(ptr);
}
typedef stdx::unique_handle< Pointer, win_delete<Pointer, Deleter> > handle_type;
};
typedef win_delete<HANDLE, CloseHandle>::handle_type winhandle;
}
}
mapped_file::mapped_file(char const* name, size_t size, unsigned access, open_mode mode,
unsigned share, unsigned hints)
{
typedef detail::generic_file::winhandle winhandle;
// always give read access
// note: if we ever remove this, we need differentiated access flags in CreateFileMappingW and MapViewOfFile!
access |= file_flags::read;
winhandle file( ::CreateFileA(
name // todo: from utf8?
, detail::generic_file::get_windows_access_flags(access)
, detail::generic_file::get_windows_sharing_flags(share, access)
, nullptr
, detail::generic_file::get_windows_open_mode(mode, access)
, detail::generic_file::get_windows_optimization_flags(hints)
, NULL
) );
if (file.get() == INVALID_HANDLE_VALUE)
throwx(std::runtime_error(name));
// Resize first to avoid creating the mapping twice
if ((access & file_flags::write) && size != 0)
{
LONGLONG longSize = size;
BOOL success = ::SetFilePointerEx(file
, reinterpret_cast<const LARGE_INTEGER&>(longSize)
, nullptr
, FILE_BEGIN)
&& ::SetEndOfFile(file);
if (!success)
throwx(std::runtime_error(name));
}
// Handles size of 0 equal to current file size
winhandle mapping( ::CreateFileMappingW(file
, nullptr
, (access & file_flags::write) ? PAGE_READWRITE : PAGE_READONLY
, 0
, 0
, nullptr
) );
if (mapping.get() == NULL)
throwx(std::runtime_error(name));
LONGLONG longSize;
if (!::GetFileSizeEx(file, reinterpret_cast<LARGE_INTEGER*>(&longSize)))
throwx(std::runtime_error(name));
// Handles size of 0 equal to end of file
this->data = (char*) ::MapViewOfFile(mapping
, (access & file_flags::write) ? (FILE_MAP_READ | FILE_MAP_WRITE) : FILE_MAP_READ
, 0
, 0
, 0
);
if (!this->data)
throwx(std::runtime_error(name));
this->size = static_cast<size_t>(longSize);
}
mapped_file::~mapped_file()
{
if (data)
::UnmapViewOfFile(data);
}
void mapped_file::prefetchAll()
{
static auto PrefetchVirtualMemory = detail::generic_file::get_prefetch_function();
if (PrefetchVirtualMemory)
{
static HANDLE process = GetCurrentProcess();
WIN32_MEMORY_RANGE_ENTRY prefetchRange = { data, size };
(*PrefetchVirtualMemory)(process, 1, &prefetchRange, 0);
}
}
namespace detail
{
namespace prompt_file
{
#define throw_com_error(x) do { \
auto winErr = (x); \
if (FAILED(winErr)) throwx( std::runtime_error(FILE_LINE_PREFIX "COM/Windows Shell") ); \
} while (false)
HRESULT com_init_unchecked()
{
return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
}
struct COM
{
COM()
{
throw_com_error(com_init_unchecked());
}
~COM()
{
CoUninitialize();
}
};
void prepareCOM()
{
static COM com;
}
struct com_delete
{
void operator ()(IUnknown* ptr) const {
ptr->Release();
}
};
template <class T>
struct com_handle_t
{
typedef stdx::unique_handle<T, com_delete> t;
};
}
} // namespace
void init_shell_on_startup()
{
char const* msg;
switch(detail::prompt_file::com_init_unchecked())
{
case S_OK:
msg = "COM explicitly initialized";
break;
case S_FALSE:
msg = "Warning: COM already initialized";
break;
case RPC_E_CHANGED_MODE:
msg = "Warning: COM already initialized IN WRONG MODE";
break;
default:
msg = "Warning: COM could not be initialized";
}
std::cerr << msg << std::endl;
}
std::vector<std::string> prompt_file(char const* current, char const* extensions
, dialog::t mode, bool multi)
{
std::vector<std::string> result;
using namespace detail::prompt_file;
prepareCOM();
com_handle_t<IFileDialog>::t pfd;
auto dialogCLSID = (mode != dialog::save) ? CLSID_FileOpenDialog : CLSID_FileSaveDialog;
throw_com_error(CoCreateInstance(dialogCLSID, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(pfd.rebind())));
com_handle_t<IFileOpenDialog>::t ofd;
if (dialogCLSID == CLSID_FileOpenDialog)
throw_com_error(pfd->QueryInterface(IID_PPV_ARGS(ofd.rebind())));
// Options
{
DWORD dwFlags = 0;
pfd->GetOptions(&dwFlags);
dwFlags |= FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR;
if (mode == dialog::folder)
dwFlags |= FOS_PICKFOLDERS;
if (multi)
dwFlags |= FOS_ALLOWMULTISELECT;
throw_com_error(pfd->SetOptions(dwFlags));
}
std::wstring_convert< std::codecvt_utf8_utf16<wchar_t> > utfcvt;
// Extensions
if (extensions)
{
auto typeStr = utfcvt.from_bytes(extensions);
auto typeCStr = typeStr.c_str();
size_t typeCnt = 1 + std::count(typeStr.begin(), typeStr.end(), L'|');
std::vector<COMDLG_FILTERSPEC> types(typeCnt);
for (size_t i = 0, off = 0; i < typeCnt; ++i)
{
size_t nextOff = typeStr.find('|', off);
if (nextOff != typeStr.npos)
typeStr[nextOff++] = 0;
auto& type = types[i];
type.pszName = type.pszSpec = typeCStr + off;
auto ass = typeStr.find('=', off);
if (ass < nextOff)
{
typeStr[ass++] = 0;
type.pszSpec = typeCStr + ass;
}
off = nextOff;
}
throw_com_error(pfd->SetFileTypes(UINT(typeCnt), types.data()));
// Unchecked, as not documented to work, but seems to always select first extension as expected
if (mode == dialog::save && typeCnt > 0)
pfd->SetDefaultExtension(L"");
}
// Initial folder
com_handle_t<IShellItem>::t currentFolderItem;
std::string parentDir;
for (; current; )
{
try
{
auto path = utfcvt.from_bytes(current);
SFGAOF folderAtt = 0;
{
struct abs_iid_deleter {
void operator ()(ITEMIDLIST_ABSOLUTE* ptr) const {
ILFree(ptr);
}
};
stdx::unique_handle<ITEMIDLIST_ABSOLUTE, abs_iid_deleter> iidl;
if (auto pathLen = GetFullPathNameW(path.c_str(), 0, nullptr, nullptr))
{
std::wstring fullPath;
fullPath.resize(pathLen);
if (GetFullPathNameW(path.c_str(), pathLen, &fullPath[0], nullptr))
path = std::move(fullPath);
}
throw_com_error(SHParseDisplayName(path.c_str(), nullptr, iidl.rebind(), SFGAO_FOLDER, &folderAtt));
throw_com_error(SHCreateItemFromIDList(iidl, IID_PPV_ARGS(currentFolderItem.rebind())));
}
if (~folderAtt & SFGAO_FOLDER || mode == dialog::folder)
{
com_handle_t<IShellItem>::t folder;
throw_com_error(currentFolderItem->GetParent(folder.rebind()));
currentFolderItem = std::move(folder);
throw_com_error(pfd->SetFileName(path.c_str()));
}
throw_com_error(pfd->SetFolder(currentFolderItem));
// success
break;
}
catch (...)
{
if (current != parentDir.c_str())
{
parentDir = dirname(current);
current = parentDir.c_str();
}
else
current = nullptr;
}
}
// Show the dialog
if (SUCCEEDED(pfd->Show(NULL)))
{
auto&& getPath = [&utfcvt](IShellItem& item) -> std::string
{
struct co_str_deleter {
void operator ()(PWSTR ptr) const {
CoTaskMemFree(ptr);
}
};
stdx::unique_handle<WCHAR, co_str_deleter> pszFilePath;
throw_com_error(item.GetDisplayName(SIGDN_FILESYSPATH, pszFilePath.rebind()));
return utfcvt.to_bytes(pszFilePath);
};
if (multi)
{
assert (ofd.get() != nullptr);
com_handle_t<IShellItemArray>::t psiResults;
throw_com_error(ofd->GetResults(psiResults.rebind()));
DWORD resultCount = 0;
psiResults->GetCount(&resultCount);
for (DWORD i = 0; i < resultCount; ++i)
{
com_handle_t<IShellItem>::t psiResult;
throw_com_error(psiResults->GetItemAt(i, psiResult.rebind()));
result.push_back( getPath(*psiResult) );
}
}
else
{
com_handle_t<IShellItem>::t psiResult;
throw_com_error(pfd->GetResult(psiResult.rebind()));
result.push_back( getPath(*psiResult) );
}
}
return result;
}
std::vector<std::string> prompt_file_compat(char const* current, char const* extensions
, dialog::t mode, bool multi)
{
std::vector<std::string> result;
using namespace detail::prompt_file;
prepareCOM();
OPENFILENAMEW ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAMEW);
ofn.hwndOwner = 0;
std::wstring fileData;
fileData.resize(1024 * 1024, 0);
ofn.lpstrFile = &fileData[0];
ofn.nMaxFile = DWORD(fileData.size());
ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_PATHMUSTEXIST;
if (mode == dialog::open)
ofn.Flags |= OFN_FILEMUSTEXIST;
if (mode == dialog::save)
ofn.Flags |= OFN_OVERWRITEPROMPT;
if (multi)
ofn.Flags |= OFN_ALLOWMULTISELECT;
std::wstring_convert< std::codecvt_utf8_utf16<wchar_t> > utfcvt;
// Extensions
std::vector<wchar_t> extensionData;
if (extensions)
{
auto typeStr = utfcvt.from_bytes(extensions);
auto typeCStr = typeStr.c_str();
size_t typeCnt = 1 + std::count(typeStr.begin(), typeStr.end(), L'|');
extensionData.resize(2 * (typeStr.size() + 1) + 1);
auto extensionDataCursor = extensionData.data();
for (size_t i = 0, off = 0; i < typeCnt; ++i)
{
auto nextOff = typeStr.find('|', off);
if (nextOff != typeStr.npos)
typeStr[nextOff++] = 0;
else
nextOff = typeStr.size() + 1;
auto ass = typeStr.find('=', off);
if (ass < nextOff)
typeStr[ass++] = 0;
wcscpy(extensionDataCursor, typeCStr + off);
extensionDataCursor += min_value(nextOff, ass) - off;
if (ass < nextOff)
{
wcscpy(extensionDataCursor, typeCStr + ass);
extensionDataCursor += nextOff - ass;
}
else
{
wcscpy(extensionDataCursor, typeCStr + off);
extensionDataCursor += nextOff - off;
}
off = nextOff;
}
// close w/ double 0
*extensionDataCursor = 0;
ofn.lpstrFilter = extensionData.data();
}
// Initial folder
std::wstring initialFolderData;
if (current)
{
auto path = utfcvt.from_bytes(current);
bool includesFile = false;
if (auto pathLen = GetFullPathNameW(path.c_str(), 0, nullptr, nullptr))
{
std::wstring fullPath;
LPWSTR filePart = nullptr;
fullPath.resize(pathLen);
if (GetFullPathNameW(path.c_str(), pathLen, &fullPath[0], &filePart))
{
path = std::move(fullPath);
includesFile = (filePart != nullptr);
}
}
if (includesFile)
wcscpy(ofn.lpstrFile, path.c_str());
else
{
// warning: moves path
initialFolderData = std::move(path);
ofn.lpstrInitialDir = initialFolderData.data();
}
}
std::wstring currDir(GetCurrentDirectoryW(0, nullptr) + 1, 0);
auto savedCurrDir = GetCurrentDirectoryW(DWORD(currDir.size()), &currDir[0]);
BOOL accepted = (mode == dialog::save) ? GetSaveFileNameW(&ofn) : GetOpenFileNameW(&ofn);
if (accepted && ofn.lpstrFile[0])
{
if (multi)
{
auto nextCursor = ofn.lpstrFile + wcslen(ofn.lpstrFile) + 1;
// Multiple selected
if (*nextCursor)
{
std::wstring pathStr = ofn.lpstrFile;
if (pathStr.back() != '\\' && pathStr.back() != '/')
pathStr.push_back('\\');
do
{
result.push_back( utfcvt.to_bytes(pathStr + nextCursor) );
nextCursor += wcslen(nextCursor) + 1;
}
while (*nextCursor);
}
// Only one file selected
else
result.push_back( utfcvt.to_bytes(ofn.lpstrFile) );
}
else
{
result.push_back( utfcvt.to_bytes(ofn.lpstrFile) );
}
}
if (savedCurrDir)
SetCurrentDirectoryW(currDir.c_str());
return result;
}
int prompt(char const* message, char const* title, choice::t choice)
{
if (!title) title = "Prompt";
UINT style = MB_TASKMODAL;
if (choice == stdx::choice::yesno)
style |= MB_ICONQUESTION | MB_YESNO;
else if (choice == stdx::choice::yesnocancel)
style |= MB_ICONQUESTION | MB_YESNOCANCEL;
else // if (choice == stdx::choice::ok)
style |= MB_ICONINFORMATION | MB_OK;
auto result = ::MessageBoxA(NULL, message, title, style);
if (result == IDYES)
return 1;
else if (result == IDNO)
return 0;
else
return -1;
}
#else
namespace detail
{
namespace generic_file
{
inline int get_posix_access_flags(unsigned access)
{
int sysaccess = O_RDONLY;
if (access & file_flags::write)
sysaccess = (access & file_flags::read) ? O_RDWR : O_WRONLY;
return sysaccess;
}
inline int get_posix_open_mode(file_flags::open_mode mode, unsigned access)
{
if (access & file_flags::write)
switch (mode)
{
case file_flags::nonexisting: return O_CREAT | O_EXCL;
case file_flags::existing: return 0;
case file_flags::new_overwrite: return O_CREAT | O_TRUNC;
default: case file_flags::open_or_new: return O_CREAT;
}
else
return 0;
}
template <class Pointer, Pointer Invalid, int (*Deleter)(Pointer)>
struct unix_delete
{
typedef stdx::nullable_handle<Pointer, Invalid> pointer;
void operator ()(Pointer ptr) const {
(*Deleter)(ptr);
}
typedef stdx::unique_handle< Pointer, unix_delete<Pointer, Invalid, Deleter> > handle_type;
};
typedef unix_delete<int, -1, close>::handle_type fdhandle;
}
}
mapped_file::mapped_file(char const* name, size_t size, unsigned access, open_mode mode,
unsigned share, unsigned hints)
{
typedef detail::generic_file::fdhandle fdhandle;
// always give read access (required by sys)
access |= file_flags::read;
fdhandle file( ::open(
name
, detail::generic_file::get_posix_access_flags(access) | detail::generic_file::get_posix_open_mode(mode, access)
, (mode_t) 0600
) );
if (file.get() == -1)
throwx(std::runtime_error(name));
size_t mapSize;
// Resize first to avoid creating the mapping twice
if ((access & file_flags::write) && size != 0)
{
mapSize = size;
auto success = ::lseek(file, mapSize - 1, SEEK_SET) != -1
&& ::write(file, "", 1) == 1;
if (!success)
throwx(std::runtime_error(name));
}
// Always map full range
else
mapSize = ::lseek(file, 0, SEEK_END);
this->data = (char*) ::mmap(nullptr
, mapSize
, (access & file_flags::write) ? PROT_READ | PROT_WRITE : PROT_READ
, MAP_SHARED
, file
, 0);
if (!this->data)
throwx(std::runtime_error(name));
this->size = mapSize;
}
mapped_file::~mapped_file()
{
if (data)
::munmap(data, size);
}
void mapped_file::prefetchAll()
{
}
void init_shell_on_startup()
{
}
std::vector<std::string> prompt_file(char const* current, char const* extensions
, dialog::t mode, bool multi)
{
std::vector<std::string> result;
if (!current) current = "$PWD";
std::stringstream dialog;
dialog << "dialog --stdout --fselect \"" << current << "\" 0 0";
struct process_close {
void operator ()(FILE* ptr) const {
pclose(ptr);
}
};
stdx::unique_handle<FILE, process_close> pipe( popen(dialog.str().c_str(), "r") );
if (!pipe) throwx(std::runtime_error("Error opening file dialog"));
std::string resultPath;
do
{
char buffer[2048];
while (fgets(buffer, arraylen(buffer), pipe) != nullptr)
resultPath += buffer;
if (!resultPath.empty())
result.push_back(resultPath);
else
break;
}
while (multi);
return result;
}
std::vector<std::string> prompt_file_compat(char const* current, char const* extensions
, dialog::t mode, bool multi)
{
return prompt_file(current, extensions, mode, multi);
}
int prompt(char const* message, char const* title, choice::t choice)
{
std::stringstream xmessage;
xmessage << "xmessage -buttons ";
enum ButtonValues { OK = 0x10, Yes, No, Cancel };
if (choice == stdx::choice::yesno || choice == stdx::choice::yesnocancel)
{
xmessage << "Yes:" << Yes << ",No:" << No;
if (choice == stdx::choice::yesnocancel)
xmessage << ",Cancel:" << Cancel;
} else // if (choice == stdx::choice::ok)
xmessage << "OK:" << OK;
xmessage << " \"" << message << '"';
auto result = ::system(xmessage.str().c_str());
if (result == Yes)
return 1;
else if (result == No)
return 0;
else
return -1;
}
#endif
namespace detail
{
namespace process_includes
{
inline char const* string_find(stdx::data_range_param<char const> str, char const val, char const* cursor)
{
return std::find(cursor, str.end(), val);
}
inline char const* string_find(stdx::data_range_param<char const> str, char const* val, char const* cursor)
{
return std::search(cursor, str.end(), val, val + strlen(val));
}
template <size_t Size>
inline char const* string_find(stdx::data_range_param<char const> str, char const (&val)[Size], char const* cursor)
{
return std::search(cursor, str.end(), val, val + Size - 1);