WinRTIO.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #include <wrl.h>
  2. #include <string>
  3. #include <DXGI.h>
  4. #include <ppltasks.h>
  5. #include <AsyncHelper.h>
  6. #include <shcore.h>
  7. #include <unordered_set>
  8. #pragma comment(lib, "ShCore.lib")
  9. #define PAL_PATH_NAME "SDLPAL"
  10. static const LARGE_INTEGER liZero = { 0 };
  11. static const void* const _SIGNATURE = &liZero;
  12. static void ConvertString(const std::string& src, std::wstring& dst)
  13. {
  14. int len = MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, nullptr, 0);
  15. dst.resize(len - 1);
  16. MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, (wchar_t*)dst.data(), len);
  17. }
  18. /*========================*/
  19. typedef struct WRT_FILE WRT_FILE;
  20. struct WRT_FILE
  21. {
  22. const void* sig;
  23. IStream* stream;
  24. CRITICAL_SECTION cs;
  25. bool readable;
  26. bool writable;
  27. bool binary;
  28. WRT_FILE() : sig(&liZero), stream(nullptr), readable(false), writable(false), binary(false) { InitializeCriticalSectionEx(&cs, 4000, 0); }
  29. WRT_FILE(Windows::Storage::Streams::IRandomAccessStream^ s, bool r, bool w, bool b)
  30. : sig(&liZero), stream(nullptr), readable(r), writable(w), binary(b)
  31. {
  32. HRESULT hr;
  33. InitializeCriticalSectionEx(&cs, 4000, 0);
  34. if (FAILED(hr = CreateStreamOverRandomAccessStream(s, IID_PPV_ARGS(&stream))))
  35. throw ref new Platform::Exception(hr);
  36. }
  37. ~WRT_FILE() { if (stream) stream->Release(); DeleteCriticalSection(&cs); }
  38. };
  39. class CriticalSection
  40. {
  41. public:
  42. CriticalSection(CRITICAL_SECTION& cs) : m_cs(cs) { EnterCriticalSection(&m_cs); }
  43. ~CriticalSection() { LeaveCriticalSection(&m_cs); }
  44. private:
  45. CRITICAL_SECTION& m_cs;
  46. };
  47. extern "C"
  48. errno_t WRT_fopen_s(WRT_FILE ** pFile, const char * _Filename, const char * _Mode)
  49. {
  50. if (nullptr == _Filename || nullptr == _Mode || nullptr == pFile) return EINVAL;
  51. HANDLE eventHandle = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
  52. std::wstring path;
  53. Platform::String^ filename;
  54. ConvertString(_Filename, path);
  55. auto ptr = (wchar_t*)path.c_str() + path.length();
  56. while (ptr >= path.c_str() && *ptr != L'/' && *ptr != L'\\') ptr--;
  57. filename = ref new Platform::String(ptr + 1);
  58. path = path.substr(0, ptr - path.c_str());
  59. size_t offset = 0;
  60. while ((offset = path.find(L'/', offset)) != std::wstring::npos)
  61. path[offset++] = L'\\';
  62. Windows::Storage::StorageFolder^ folder;
  63. try
  64. {
  65. folder = AWait(Windows::Storage::StorageFolder::GetFolderFromPathAsync(ref new Platform::String(path.c_str())), eventHandle);
  66. }
  67. catch (Platform::AccessDeniedException^)
  68. {
  69. //int index = path.length() - 1;
  70. //if (_wcsnicmp(g_basefolder->Path->Begin(), path.c_str(), g_basefolder->Path->Length()) == 0)
  71. // folder = g_basefolder;
  72. //else if (_wcsnicmp(g_savefolder->Path->Begin(), path.c_str(), g_savefolder->Path->Length()) == 0)
  73. // folder = g_savefolder;
  74. //else
  75. return EACCES;
  76. if (path.length() > folder->Path->Length())
  77. {
  78. auto folder_length = folder->Path->Length();
  79. if (path[folder_length] == L'\\') folder_length++;
  80. try
  81. {
  82. for (auto next = path.find(L'\\', folder_length); next != std::wstring::npos; next = path.find(L'\\', (folder_length = next + 1)))
  83. folder = AWait(folder->GetFolderAsync(ref new Platform::String(path.substr(folder_length, next - folder_length).c_str())), eventHandle);
  84. folder = AWait(folder->GetFolderAsync(ref new Platform::String(path.substr(folder_length).c_str())), eventHandle);
  85. }
  86. catch (Platform::Exception^)
  87. {
  88. return EIO;
  89. }
  90. }
  91. }
  92. catch (Platform::Exception^)
  93. {
  94. return EIO;
  95. }
  96. WRT_FILE* ret = nullptr;
  97. try
  98. {
  99. Windows::Storage::StorageFile^ file;
  100. bool r, w;
  101. switch (*_Mode)
  102. {
  103. case 'a': file = AWait(folder->CreateFileAsync(filename, Windows::Storage::CreationCollisionOption::OpenIfExists), eventHandle); w = true; r = false; break;
  104. case 'w': file = AWait(folder->CreateFileAsync(filename, Windows::Storage::CreationCollisionOption::ReplaceExisting), eventHandle); w = true; r = false; break;
  105. case 'r': file = AWait(folder->GetFileAsync(filename), eventHandle); w = false; r = true; break;
  106. default: CloseHandle(eventHandle); return EINVAL;
  107. }
  108. if (file)
  109. {
  110. bool b = false;
  111. for (size_t i = 1; i < strlen(_Mode); i++)
  112. {
  113. switch (_Mode[i])
  114. {
  115. case '+': r = w = true; break;
  116. case 'b': b = true; break;
  117. case 't': b = false; break;
  118. default: return EINVAL;
  119. }
  120. }
  121. ret = new WRT_FILE(AWait(file->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  122. }
  123. CloseHandle(eventHandle);
  124. }
  125. catch (Platform::Exception^)
  126. {
  127. return EIO;
  128. }
  129. *pFile = ret;
  130. return 0;
  131. }
  132. extern "C"
  133. WRT_FILE* WRT_fopen(const char * _Filename, const char * _Mode)
  134. {
  135. WRT_FILE* ret;
  136. int err = WRT_fopen_s(&ret, _Filename, _Mode);
  137. _set_errno(err);
  138. return err ? nullptr : ret;
  139. }
  140. extern "C"
  141. int WRT_fclose(WRT_FILE * _File)
  142. {
  143. if (!_File || _File->sig != _SIGNATURE) return fclose((FILE*)_File);
  144. delete _File;
  145. return 0;
  146. }
  147. extern "C"
  148. int WRT_feof(WRT_FILE * _File)
  149. {
  150. if (!_File || _File->sig != _SIGNATURE) return feof((FILE*)_File);
  151. STATSTG st;
  152. ULARGE_INTEGER uli;
  153. CriticalSection cs(_File->cs);
  154. if (SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, &uli)) &&
  155. SUCCEEDED(_File->stream->Stat(&st, STATFLAG_NONAME)))
  156. return uli.QuadPart >= st.cbSize.QuadPart;
  157. else
  158. return 1;
  159. }
  160. extern "C"
  161. int WRT_fseeki64(WRT_FILE * _File, long long _Offset, int _Origin)
  162. {
  163. if (!_File || _File->sig != _SIGNATURE) return _fseeki64((FILE*)_File, _Offset, _Origin);
  164. CriticalSection cs(_File->cs);
  165. LARGE_INTEGER liOffset;
  166. liOffset.QuadPart = _Offset;
  167. return SUCCEEDED(_File->stream->Seek(liOffset, _Origin, NULL)) ? 0 : -1;
  168. }
  169. extern "C"
  170. int WRT_fseek(WRT_FILE * _File, long _Offset, int _Origin)
  171. {
  172. return WRT_fseeki64(_File, _Offset, _Origin);
  173. }
  174. extern "C"
  175. long long WRT_ftelli64(WRT_FILE * _File)
  176. {
  177. if (!_File || _File->sig != _SIGNATURE) return _ftelli64((FILE*)_File);
  178. CriticalSection cs(_File->cs);
  179. unsigned long long pos;
  180. return SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, (PULARGE_INTEGER)&pos)) ? pos : -1;
  181. }
  182. extern "C"
  183. size_t WRT_ftell(WRT_FILE * _File)
  184. {
  185. return (size_t)WRT_ftelli64(_File);
  186. }
  187. extern "C"
  188. size_t WRT_fread(void * _DstBuf, size_t _ElementSize, size_t _Count, WRT_FILE * _File)
  189. {
  190. if (!_File || _File->sig != _SIGNATURE) return fread(_DstBuf, _ElementSize, _Count, (FILE*)_File);
  191. if (!_File->readable || _ElementSize == 0 || _Count == 0 || !_DstBuf) return 0;
  192. CriticalSection cs(_File->cs);
  193. unsigned long cbRead;
  194. return SUCCEEDED(_File->stream->Read(_DstBuf, _ElementSize * _Count, &cbRead)) ? cbRead / _ElementSize : 0;
  195. }
  196. extern "C"
  197. size_t WRT_fwrite(const void * _Str, size_t _Size, size_t _Count, WRT_FILE * _File)
  198. {
  199. if (!_File || _File->sig != _SIGNATURE) return fwrite(_Str, _Size, _Count, (FILE*)_File);
  200. if (!_File->writable || !_Str || _Size == 0 || _Count == 0) return 0;
  201. CriticalSection cs(_File->cs);
  202. unsigned long cbWrite;
  203. return SUCCEEDED(_File->stream->Write(_Str, _Size * _Count, &cbWrite)) ? cbWrite / _Size : 0;
  204. }
  205. extern "C"
  206. int WRT_fflush(WRT_FILE * _File)
  207. {
  208. if (!_File || _File->sig != _SIGNATURE) return fflush((FILE*)_File);
  209. if (!_File->writable) return 0;
  210. CriticalSection cs(_File->cs);
  211. return SUCCEEDED(_File->stream->Commit(STGC_DEFAULT)) ? 0 : EOF;
  212. }
  213. static int WRT_fgetc_nolock(WRT_FILE * _File)
  214. {
  215. unsigned long cbRead;
  216. unsigned char buf;
  217. return _File->stream->Read(&buf, 1, &cbRead) == S_OK ? buf : EOF;
  218. }
  219. extern "C"
  220. int WRT_fgetc(WRT_FILE * _File)
  221. {
  222. if (!_File || _File->sig != _SIGNATURE) return fgetc((FILE*)_File);
  223. CriticalSection cs(_File->cs);
  224. return _File->readable ? WRT_fgetc_nolock(_File) : EOF;
  225. }
  226. extern "C"
  227. char* WRT_fgets(char * _Buf, int _MaxCount, WRT_FILE * _File)
  228. {
  229. if (!_File || _File->sig != _SIGNATURE) return fgets(_Buf, _MaxCount, (FILE*)_File);
  230. if (!_File->readable || !_Buf || _MaxCount <= 0) return nullptr;
  231. CriticalSection cs(_File->cs);
  232. int n = 0, flag = 0, ch;
  233. while (n < _MaxCount - 1 && EOF != (ch = WRT_fgetc_nolock(_File)))
  234. {
  235. if (flag)
  236. {
  237. if (ch != '\n')
  238. _Buf[n++] = '\r';
  239. flag = 0;
  240. }
  241. if (ch != '\r')
  242. {
  243. _Buf[n++] = ch;
  244. if (ch == '\n') break;
  245. }
  246. else
  247. flag = 1;
  248. }
  249. if (n > 0)
  250. {
  251. _Buf[n] = '\0';
  252. return _Buf;
  253. }
  254. else
  255. return nullptr;
  256. }
  257. extern "C"
  258. int WRT_fputc(int _Ch, WRT_FILE * _File)
  259. {
  260. if (!_File || _File->sig != _SIGNATURE) return fputc(_Ch, (FILE*)_File);
  261. return EOF;
  262. }
  263. extern "C"
  264. int WRT_fputs(const char * _Str, WRT_FILE * _File)
  265. {
  266. if (!_File || _File->sig != _SIGNATURE) return fputs(_Str, (FILE*)_File);
  267. return EOF;
  268. }