WinRTIO.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 <map>
  28. #include <DXGI.h>
  29. #include <shcore.h>
  30. #include <unordered_set>
  31. #include "AsyncHelper.h"
  32. #include "StringHelper.h"
  33. #pragma comment(lib, "ShCore.lib")
  34. #define PAL_PATH_NAME "SDLPAL"
  35. static const LARGE_INTEGER liZero = { 0 };
  36. static const void* const _SIGNATURE = &liZero;
  37. /*========================*/
  38. typedef struct WRT_FILE WRT_FILE;
  39. struct WRT_FILE
  40. {
  41. const void* sig;
  42. IStream* stream;
  43. CRITICAL_SECTION cs;
  44. bool readable;
  45. bool writable;
  46. bool binary;
  47. WRT_FILE() : sig(&liZero), stream(nullptr), readable(false), writable(false), binary(false) { InitializeCriticalSectionEx(&cs, 4000, 0); }
  48. WRT_FILE(Windows::Storage::Streams::IRandomAccessStream^ s, bool r, bool w, bool b)
  49. : sig(&liZero), stream(nullptr), readable(r), writable(w), binary(b)
  50. {
  51. HRESULT hr;
  52. InitializeCriticalSectionEx(&cs, 4000, 0);
  53. if (FAILED(hr = CreateStreamOverRandomAccessStream(s, IID_PPV_ARGS(&stream))))
  54. throw ref new Platform::Exception(hr);
  55. }
  56. ~WRT_FILE() { if (stream) stream->Release(); DeleteCriticalSection(&cs); }
  57. };
  58. static std::map<std::string, Windows::Storage::StorageFile^> g_specialFiles;
  59. static std::map<std::string, Windows::Storage::StorageFolder^> g_specialFolders;
  60. class CriticalSection
  61. {
  62. public:
  63. CriticalSection(CRITICAL_SECTION& cs) : m_cs(cs) { EnterCriticalSection(&m_cs); }
  64. ~CriticalSection() { LeaveCriticalSection(&m_cs); }
  65. private:
  66. CRITICAL_SECTION& m_cs;
  67. };
  68. class Event
  69. {
  70. public:
  71. Event() : _eventHandle(CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS)) {}
  72. ~Event() { CloseHandle(_eventHandle); }
  73. operator HANDLE() { return _eventHandle; }
  74. private:
  75. HANDLE _eventHandle;
  76. };
  77. static const std::string get_directory(const char* _Filename)
  78. {
  79. auto ptr = _Filename;
  80. while (*ptr == '/' || *ptr == '\\') ptr++;
  81. std::string directory((ptr != _Filename) ? "\\" : "");
  82. while (*ptr)
  83. {
  84. std::string temp;
  85. auto pos = ptr;
  86. while (*pos && *pos != '/' && *pos != '\\') pos++;
  87. if (*pos)
  88. {
  89. directory.append(ptr, pos - ptr);
  90. directory.append("\\");
  91. }
  92. while (*pos == '/' || *pos == '\\') pos++;
  93. ptr = pos;
  94. }
  95. return directory;
  96. }
  97. static const std::string get_filename(const char* _Filename)
  98. {
  99. auto ptr = _Filename + strlen(_Filename);
  100. while (ptr > _Filename && *ptr != '/' && *ptr != '\\') ptr--;
  101. if (*ptr == '/' || *ptr == '\\') ptr++;
  102. return ptr;
  103. }
  104. extern "C" std::map<std::string, Windows::Storage::StorageFile^>* get_special_files_map() { return &g_specialFiles; }
  105. extern "C" std::map<std::string, Windows::Storage::StorageFolder^>* get_special_folders_map() { return &g_specialFolders; }
  106. extern "C"
  107. errno_t WRT_fopen_s(WRT_FILE ** pFile, const char * _Filename, const char * _Mode)
  108. {
  109. if (nullptr == _Filename || nullptr == _Mode || nullptr == pFile) return EINVAL;
  110. *pFile = nullptr;
  111. bool r, w, b = false;
  112. switch (*_Mode)
  113. {
  114. case 'a': w = true; r = false; break;
  115. case 'w': w = true; r = false; break;
  116. case 'r': w = false; r = true; break;
  117. default: return EINVAL;
  118. }
  119. for (size_t i = 1; i < strlen(_Mode); i++)
  120. {
  121. switch (_Mode[i])
  122. {
  123. case '+': r = w = true; break;
  124. case 'b': b = true; break;
  125. case 't': b = false; break;
  126. default: return EINVAL;
  127. }
  128. }
  129. Event eventHandle;
  130. // If the file belongs to so-called 'special files' (i.e., specified in configuration file), then return its object directly
  131. if (g_specialFiles.find(_Filename) != g_specialFiles.end())
  132. {
  133. auto file = g_specialFiles[_Filename];
  134. try
  135. {
  136. *pFile = new WRT_FILE(AWait(file->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  137. }
  138. catch (Platform::AccessDeniedException^)
  139. {
  140. return EACCES;
  141. }
  142. catch (Platform::Exception^)
  143. {
  144. return EIO;
  145. }
  146. return 0;
  147. }
  148. auto directory = get_directory(_Filename);
  149. auto filename = get_filename(_Filename);
  150. Windows::Storage::StorageFolder^ folder = nullptr;
  151. // If the file's folder belongs to so-called 'special folders' (i.e., specified in configuration file), then use the cache folder object
  152. for (auto i = g_specialFolders.begin(); directory.length() > 0 && i != g_specialFolders.end(); i++)
  153. {
  154. if (_strnicmp(i->first.c_str(), directory.c_str(), i->first.size()) == 0)
  155. {
  156. folder = i->second;
  157. if (directory.length() > i->first.length())
  158. {
  159. size_t pos = i->first.length(), next = directory.find('\\', pos);
  160. while (next != std::string::npos)
  161. {
  162. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], next - pos))), eventHandle);
  163. next = directory.find('\\', pos = next + 1);
  164. }
  165. if (pos < directory.length())
  166. {
  167. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], directory.length() - pos))), eventHandle);
  168. }
  169. }
  170. }
  171. }
  172. // The try get folder directly by its full path
  173. if (!folder && directory.length())
  174. {
  175. folder = AWait(Windows::Storage::StorageFolder::GetFolderFromPathAsync(ConvertString(directory)), eventHandle);
  176. }
  177. // As a last sort, use app's local folder
  178. if (!folder)
  179. {
  180. folder = Windows::Storage::ApplicationData::Current->LocalFolder;
  181. }
  182. try
  183. {
  184. Windows::Storage::StorageFile^ file = nullptr;
  185. switch (*_Mode)
  186. {
  187. case 'a':
  188. file = AWait(folder->CreateFileAsync(ConvertString(filename), Windows::Storage::CreationCollisionOption::OpenIfExists), eventHandle);
  189. break;
  190. case 'w':
  191. file = AWait(folder->CreateFileAsync(ConvertString(filename), Windows::Storage::CreationCollisionOption::ReplaceExisting), eventHandle);
  192. break;
  193. case 'r':
  194. file = AWait(folder->GetFileAsync(ConvertString(filename)), eventHandle);
  195. break;
  196. }
  197. if (file)
  198. {
  199. *pFile = new WRT_FILE(AWait(file->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  200. }
  201. }
  202. catch (Platform::AccessDeniedException^)
  203. {
  204. return EACCES;
  205. }
  206. catch (Platform::Exception^)
  207. {
  208. return EIO;
  209. }
  210. return 0;
  211. }
  212. extern "C"
  213. WRT_FILE* WRT_fopen(const char * _Filename, const char * _Mode)
  214. {
  215. WRT_FILE* ret;
  216. int err = WRT_fopen_s(&ret, _Filename, _Mode);
  217. _set_errno(err);
  218. return err ? nullptr : ret;
  219. }
  220. extern "C"
  221. int WRT_fclose(WRT_FILE * _File)
  222. {
  223. if (!_File || _File->sig != _SIGNATURE) return fclose((FILE*)_File);
  224. delete _File;
  225. return 0;
  226. }
  227. extern "C"
  228. int WRT_feof(WRT_FILE * _File)
  229. {
  230. if (!_File || _File->sig != _SIGNATURE) return feof((FILE*)_File);
  231. STATSTG st;
  232. ULARGE_INTEGER uli;
  233. CriticalSection cs(_File->cs);
  234. if (SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, &uli)) &&
  235. SUCCEEDED(_File->stream->Stat(&st, STATFLAG_NONAME)))
  236. return uli.QuadPart >= st.cbSize.QuadPart;
  237. else
  238. return 1;
  239. }
  240. extern "C"
  241. int WRT_fseeki64(WRT_FILE * _File, long long _Offset, int _Origin)
  242. {
  243. if (!_File || _File->sig != _SIGNATURE) return _fseeki64((FILE*)_File, _Offset, _Origin);
  244. CriticalSection cs(_File->cs);
  245. LARGE_INTEGER liOffset;
  246. liOffset.QuadPart = _Offset;
  247. return SUCCEEDED(_File->stream->Seek(liOffset, _Origin, NULL)) ? 0 : -1;
  248. }
  249. extern "C"
  250. int WRT_fseek(WRT_FILE * _File, long _Offset, int _Origin)
  251. {
  252. return WRT_fseeki64(_File, _Offset, _Origin);
  253. }
  254. extern "C"
  255. long long WRT_ftelli64(WRT_FILE * _File)
  256. {
  257. if (!_File || _File->sig != _SIGNATURE) return _ftelli64((FILE*)_File);
  258. CriticalSection cs(_File->cs);
  259. unsigned long long pos;
  260. return SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, (PULARGE_INTEGER)&pos)) ? pos : -1;
  261. }
  262. extern "C"
  263. size_t WRT_ftell(WRT_FILE * _File)
  264. {
  265. return (size_t)WRT_ftelli64(_File);
  266. }
  267. extern "C"
  268. size_t WRT_fread(void * _DstBuf, size_t _ElementSize, size_t _Count, WRT_FILE * _File)
  269. {
  270. if (!_File || _File->sig != _SIGNATURE) return fread(_DstBuf, _ElementSize, _Count, (FILE*)_File);
  271. if (!_File->readable || _ElementSize == 0 || _Count == 0 || !_DstBuf) return 0;
  272. CriticalSection cs(_File->cs);
  273. unsigned long cbRead;
  274. return SUCCEEDED(_File->stream->Read(_DstBuf, _ElementSize * _Count, &cbRead)) ? cbRead / _ElementSize : 0;
  275. }
  276. extern "C"
  277. size_t WRT_fwrite(const void * _Str, size_t _Size, size_t _Count, WRT_FILE * _File)
  278. {
  279. if (!_File || _File->sig != _SIGNATURE) return fwrite(_Str, _Size, _Count, (FILE*)_File);
  280. if (!_File->writable || !_Str || _Size == 0 || _Count == 0) return 0;
  281. CriticalSection cs(_File->cs);
  282. unsigned long cbWrite;
  283. return SUCCEEDED(_File->stream->Write(_Str, _Size * _Count, &cbWrite)) ? cbWrite / _Size : 0;
  284. }
  285. extern "C"
  286. int WRT_fflush(WRT_FILE * _File)
  287. {
  288. if (!_File || _File->sig != _SIGNATURE) return fflush((FILE*)_File);
  289. if (!_File->writable) return 0;
  290. CriticalSection cs(_File->cs);
  291. return SUCCEEDED(_File->stream->Commit(STGC_DEFAULT)) ? 0 : EOF;
  292. }
  293. static int WRT_fgetc_nolock(WRT_FILE * _File)
  294. {
  295. unsigned long cbRead;
  296. unsigned char buf;
  297. return _File->stream->Read(&buf, 1, &cbRead) == S_OK ? buf : EOF;
  298. }
  299. extern "C"
  300. int WRT_fgetc(WRT_FILE * _File)
  301. {
  302. if (!_File || _File->sig != _SIGNATURE) return fgetc((FILE*)_File);
  303. CriticalSection cs(_File->cs);
  304. return _File->readable ? WRT_fgetc_nolock(_File) : EOF;
  305. }
  306. extern "C"
  307. char* WRT_fgets(char * _Buf, int _MaxCount, WRT_FILE * _File)
  308. {
  309. if (!_File || _File->sig != _SIGNATURE) return fgets(_Buf, _MaxCount, (FILE*)_File);
  310. if (!_File->readable || !_Buf || _MaxCount <= 0) return nullptr;
  311. CriticalSection cs(_File->cs);
  312. int n = 0, flag = 0, ch;
  313. while (n < _MaxCount - 1 && EOF != (ch = WRT_fgetc_nolock(_File)))
  314. {
  315. if (flag)
  316. {
  317. if (ch != '\n')
  318. _Buf[n++] = '\r';
  319. flag = 0;
  320. }
  321. if (ch != '\r')
  322. {
  323. _Buf[n++] = ch;
  324. if (ch == '\n') break;
  325. }
  326. else
  327. flag = 1;
  328. }
  329. if (n > 0)
  330. {
  331. _Buf[n] = '\0';
  332. return _Buf;
  333. }
  334. else
  335. return nullptr;
  336. }
  337. extern "C"
  338. int WRT_fputc(int _Ch, WRT_FILE * _File)
  339. {
  340. if (!_File || _File->sig != _SIGNATURE) return fputc(_Ch, (FILE*)_File);
  341. CriticalSection cs(_File->cs);
  342. unsigned long cbWrite;
  343. return _File->writable && _File->stream->Write(&_Ch, 1, &cbWrite) == S_OK ? cbWrite : EOF;
  344. }
  345. extern "C"
  346. int WRT_fputs(const char * _Str, WRT_FILE * _File)
  347. {
  348. if (!_File || _File->sig != _SIGNATURE) return fputs(_Str, (FILE*)_File);
  349. if (!_File->writable || !_Str) return EOF;
  350. const char *start = _Str;
  351. int length = strlen(_Str);
  352. unsigned long cbWrite;
  353. const char crlf[] = { '\r', '\n' };
  354. CriticalSection cs(_File->cs);
  355. while (true)
  356. {
  357. const char *ptr = start;
  358. while (*ptr && *ptr != '\n') ptr++;
  359. if (_File->stream->Write(start, ptr - start, &cbWrite) != S_OK)
  360. return EOF;
  361. if (*ptr == '\n')
  362. {
  363. if (_File->stream->Write(crlf, 2, &cbWrite) != S_OK)
  364. return EOF;
  365. else
  366. start = ptr + 1;
  367. }
  368. else
  369. break;
  370. }
  371. return length;
  372. }