WinRTIO.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 4; c-file-style: "linux" -*- */
  2. //
  3. // WinRTIO.cpp: UWP C-style file I/O wrapper for SDLPal.
  4. // Author: Lou Yihua @ 2016-2017
  5. //
  6. // Copyright (c) 2009-2011, Wei Mingzhi <whistler_wmz@users.sf.net>.
  7. // Copyright (c) 2011-2017 SDLPAL development team.
  8. // All rights reserved.
  9. //
  10. // This file is part of SDLPAL.
  11. //
  12. // SDLPAL is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. #include <wrl.h>
  26. #include <string>
  27. #include <DXGI.h>
  28. #include <shcore.h>
  29. #include <unordered_set>
  30. #include "AsyncHelper.h"
  31. #include "StringHelper.h"
  32. #pragma comment(lib, "ShCore.lib")
  33. #define PAL_PATH_NAME "SDLPAL"
  34. static const LARGE_INTEGER liZero = { 0 };
  35. static const void* const _SIGNATURE = &liZero;
  36. /*========================*/
  37. typedef struct WRT_FILE WRT_FILE;
  38. struct WRT_FILE
  39. {
  40. const void* sig;
  41. IStream* stream;
  42. CRITICAL_SECTION cs;
  43. bool readable;
  44. bool writable;
  45. bool binary;
  46. WRT_FILE() : sig(&liZero), stream(nullptr), readable(false), writable(false), binary(false) { InitializeCriticalSectionEx(&cs, 4000, 0); }
  47. WRT_FILE(Windows::Storage::Streams::IRandomAccessStream^ s, bool r, bool w, bool b)
  48. : sig(&liZero), stream(nullptr), readable(r), writable(w), binary(b)
  49. {
  50. HRESULT hr;
  51. InitializeCriticalSectionEx(&cs, 4000, 0);
  52. if (FAILED(hr = CreateStreamOverRandomAccessStream(s, IID_PPV_ARGS(&stream))))
  53. throw ref new Platform::Exception(hr);
  54. }
  55. ~WRT_FILE() { if (stream) stream->Release(); DeleteCriticalSection(&cs); }
  56. };
  57. class CriticalSection
  58. {
  59. public:
  60. CriticalSection(CRITICAL_SECTION& cs) : m_cs(cs) { EnterCriticalSection(&m_cs); }
  61. ~CriticalSection() { LeaveCriticalSection(&m_cs); }
  62. private:
  63. CRITICAL_SECTION& m_cs;
  64. };
  65. class Event
  66. {
  67. public:
  68. Event() : _eventHandle(CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS)) {}
  69. ~Event() { CloseHandle(_eventHandle); }
  70. operator HANDLE() { return _eventHandle; }
  71. private:
  72. HANDLE _eventHandle;
  73. };
  74. extern "C"
  75. errno_t WRT_fopen_s(WRT_FILE ** pFile, const char * _Filename, const char * _Mode)
  76. {
  77. if (nullptr == _Filename || nullptr == _Mode || nullptr == pFile) return EINVAL;
  78. auto ptr = _Filename;
  79. while (*ptr == '/' || *ptr == '\\') ptr++;
  80. Platform::String^ directory = ref new Platform::String((ptr != _Filename) ? L"\\" : L"");
  81. Platform::String^ filename;
  82. while (*ptr)
  83. {
  84. std::wstring temp;
  85. auto pos = ptr;
  86. while (*pos && *pos != '/' && *pos != '\\') pos++;
  87. if (*pos)
  88. {
  89. ConvertString(std::string(ptr, pos - ptr + 1), temp); temp[pos - ptr] = L'\\';
  90. directory = Platform::String::Concat(directory, ref new Platform::String(temp.c_str()));
  91. }
  92. else
  93. {
  94. ConvertString(std::string(ptr, pos - ptr), temp);
  95. filename = ref new Platform::String(temp.c_str());
  96. }
  97. while (*pos == '/' || *pos == '\\') pos++;
  98. ptr = pos;
  99. }
  100. if (directory->Length() == 0)
  101. {
  102. directory = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
  103. }
  104. bool r, w, b = false;
  105. switch (*_Mode)
  106. {
  107. case 'a': w = true; r = false; break;
  108. case 'w': w = true; r = false; break;
  109. case 'r': w = false; r = true; break;
  110. default: delete filename; return EINVAL;
  111. }
  112. for (size_t i = 1; i < strlen(_Mode); i++)
  113. {
  114. switch (_Mode[i])
  115. {
  116. case '+': r = w = true; break;
  117. case 'b': b = true; break;
  118. case 't': b = false; break;
  119. default: delete filename; return EINVAL;
  120. }
  121. }
  122. *pFile = nullptr;
  123. try
  124. {
  125. Event eventHandle;
  126. Windows::Storage::StorageFolder^ folder = AWait(Windows::Storage::StorageFolder::GetFolderFromPathAsync(directory), eventHandle);
  127. Windows::Storage::StorageFile^ file = nullptr;
  128. switch (*_Mode)
  129. {
  130. case 'a':
  131. file = AWait(folder->CreateFileAsync(filename, Windows::Storage::CreationCollisionOption::OpenIfExists), eventHandle);
  132. break;
  133. case 'w':
  134. file = AWait(folder->CreateFileAsync(filename, Windows::Storage::CreationCollisionOption::ReplaceExisting), eventHandle);
  135. break;
  136. case 'r':
  137. file = AWait(folder->GetFileAsync(filename), eventHandle);
  138. break;
  139. }
  140. if (file)
  141. {
  142. *pFile = new WRT_FILE(AWait(file->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  143. }
  144. }
  145. catch (Platform::AccessDeniedException^)
  146. {
  147. return EACCES;
  148. }
  149. catch (Platform::Exception^)
  150. {
  151. return EIO;
  152. }
  153. return 0;
  154. }
  155. extern "C"
  156. WRT_FILE* WRT_fopen(const char * _Filename, const char * _Mode)
  157. {
  158. WRT_FILE* ret;
  159. int err = WRT_fopen_s(&ret, _Filename, _Mode);
  160. _set_errno(err);
  161. return err ? nullptr : ret;
  162. }
  163. extern "C"
  164. int WRT_fclose(WRT_FILE * _File)
  165. {
  166. if (!_File || _File->sig != _SIGNATURE) return fclose((FILE*)_File);
  167. delete _File;
  168. return 0;
  169. }
  170. extern "C"
  171. int WRT_feof(WRT_FILE * _File)
  172. {
  173. if (!_File || _File->sig != _SIGNATURE) return feof((FILE*)_File);
  174. STATSTG st;
  175. ULARGE_INTEGER uli;
  176. CriticalSection cs(_File->cs);
  177. if (SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, &uli)) &&
  178. SUCCEEDED(_File->stream->Stat(&st, STATFLAG_NONAME)))
  179. return uli.QuadPart >= st.cbSize.QuadPart;
  180. else
  181. return 1;
  182. }
  183. extern "C"
  184. int WRT_fseeki64(WRT_FILE * _File, long long _Offset, int _Origin)
  185. {
  186. if (!_File || _File->sig != _SIGNATURE) return _fseeki64((FILE*)_File, _Offset, _Origin);
  187. CriticalSection cs(_File->cs);
  188. LARGE_INTEGER liOffset;
  189. liOffset.QuadPart = _Offset;
  190. return SUCCEEDED(_File->stream->Seek(liOffset, _Origin, NULL)) ? 0 : -1;
  191. }
  192. extern "C"
  193. int WRT_fseek(WRT_FILE * _File, long _Offset, int _Origin)
  194. {
  195. return WRT_fseeki64(_File, _Offset, _Origin);
  196. }
  197. extern "C"
  198. long long WRT_ftelli64(WRT_FILE * _File)
  199. {
  200. if (!_File || _File->sig != _SIGNATURE) return _ftelli64((FILE*)_File);
  201. CriticalSection cs(_File->cs);
  202. unsigned long long pos;
  203. return SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, (PULARGE_INTEGER)&pos)) ? pos : -1;
  204. }
  205. extern "C"
  206. size_t WRT_ftell(WRT_FILE * _File)
  207. {
  208. return (size_t)WRT_ftelli64(_File);
  209. }
  210. extern "C"
  211. size_t WRT_fread(void * _DstBuf, size_t _ElementSize, size_t _Count, WRT_FILE * _File)
  212. {
  213. if (!_File || _File->sig != _SIGNATURE) return fread(_DstBuf, _ElementSize, _Count, (FILE*)_File);
  214. if (!_File->readable || _ElementSize == 0 || _Count == 0 || !_DstBuf) return 0;
  215. CriticalSection cs(_File->cs);
  216. unsigned long cbRead;
  217. return SUCCEEDED(_File->stream->Read(_DstBuf, _ElementSize * _Count, &cbRead)) ? cbRead / _ElementSize : 0;
  218. }
  219. extern "C"
  220. size_t WRT_fwrite(const void * _Str, size_t _Size, size_t _Count, WRT_FILE * _File)
  221. {
  222. if (!_File || _File->sig != _SIGNATURE) return fwrite(_Str, _Size, _Count, (FILE*)_File);
  223. if (!_File->writable || !_Str || _Size == 0 || _Count == 0) return 0;
  224. CriticalSection cs(_File->cs);
  225. unsigned long cbWrite;
  226. return SUCCEEDED(_File->stream->Write(_Str, _Size * _Count, &cbWrite)) ? cbWrite / _Size : 0;
  227. }
  228. extern "C"
  229. int WRT_fflush(WRT_FILE * _File)
  230. {
  231. if (!_File || _File->sig != _SIGNATURE) return fflush((FILE*)_File);
  232. if (!_File->writable) return 0;
  233. CriticalSection cs(_File->cs);
  234. return SUCCEEDED(_File->stream->Commit(STGC_DEFAULT)) ? 0 : EOF;
  235. }
  236. static int WRT_fgetc_nolock(WRT_FILE * _File)
  237. {
  238. unsigned long cbRead;
  239. unsigned char buf;
  240. return _File->stream->Read(&buf, 1, &cbRead) == S_OK ? buf : EOF;
  241. }
  242. extern "C"
  243. int WRT_fgetc(WRT_FILE * _File)
  244. {
  245. if (!_File || _File->sig != _SIGNATURE) return fgetc((FILE*)_File);
  246. CriticalSection cs(_File->cs);
  247. return _File->readable ? WRT_fgetc_nolock(_File) : EOF;
  248. }
  249. extern "C"
  250. char* WRT_fgets(char * _Buf, int _MaxCount, WRT_FILE * _File)
  251. {
  252. if (!_File || _File->sig != _SIGNATURE) return fgets(_Buf, _MaxCount, (FILE*)_File);
  253. if (!_File->readable || !_Buf || _MaxCount <= 0) return nullptr;
  254. CriticalSection cs(_File->cs);
  255. int n = 0, flag = 0, ch;
  256. while (n < _MaxCount - 1 && EOF != (ch = WRT_fgetc_nolock(_File)))
  257. {
  258. if (flag)
  259. {
  260. if (ch != '\n')
  261. _Buf[n++] = '\r';
  262. flag = 0;
  263. }
  264. if (ch != '\r')
  265. {
  266. _Buf[n++] = ch;
  267. if (ch == '\n') break;
  268. }
  269. else
  270. flag = 1;
  271. }
  272. if (n > 0)
  273. {
  274. _Buf[n] = '\0';
  275. return _Buf;
  276. }
  277. else
  278. return nullptr;
  279. }
  280. extern "C"
  281. int WRT_fputc(int _Ch, WRT_FILE * _File)
  282. {
  283. if (!_File || _File->sig != _SIGNATURE) return fputc(_Ch, (FILE*)_File);
  284. CriticalSection cs(_File->cs);
  285. unsigned long cbWrite;
  286. return _File->writable && _File->stream->Write(&_Ch, 1, &cbWrite) == S_OK ? cbWrite : EOF;
  287. }
  288. extern "C"
  289. int WRT_fputs(const char * _Str, WRT_FILE * _File)
  290. {
  291. if (!_File || _File->sig != _SIGNATURE) return fputs(_Str, (FILE*)_File);
  292. if (!_File->writable || !_Str) return EOF;
  293. const char *start = _Str;
  294. int length = strlen(_Str);
  295. unsigned long cbWrite;
  296. const char crlf[] = { '\r', '\n' };
  297. CriticalSection cs(_File->cs);
  298. while (true)
  299. {
  300. const char *ptr = start;
  301. while (*ptr && *ptr != '\n') ptr++;
  302. if (_File->stream->Write(start, ptr - start, &cbWrite) != S_OK)
  303. return EOF;
  304. if (*ptr == '\n')
  305. {
  306. if (_File->stream->Write(crlf, 2, &cbWrite) != S_OK)
  307. return EOF;
  308. else
  309. start = ptr + 1;
  310. }
  311. else
  312. break;
  313. }
  314. return length;
  315. }