WinRTIO.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. try
  130. {
  131. Event eventHandle;
  132. // If the file belongs to so-called 'special files' (i.e., specified in configuration file), then return its object directly
  133. if (g_specialFiles.find(_Filename) != g_specialFiles.end())
  134. {
  135. *pFile = new WRT_FILE(AWait(g_specialFiles[_Filename]->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  136. return 0;
  137. }
  138. auto directory = get_directory(_Filename);
  139. auto filename = get_filename(_Filename);
  140. Windows::Storage::StorageFolder^ folder = nullptr;
  141. // If the file's folder belongs to so-called 'special folders' (i.e., specified in configuration file), then use the cache folder object
  142. for (auto i = g_specialFolders.begin(); directory.length() > 0 && i != g_specialFolders.end(); i++)
  143. {
  144. if (_strnicmp(i->first.c_str(), directory.c_str(), i->first.size()) == 0)
  145. {
  146. folder = i->second;
  147. if (directory.length() > i->first.length())
  148. {
  149. size_t pos = i->first.length(), next = directory.find('\\', pos);
  150. while (next != std::string::npos)
  151. {
  152. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], next - pos))), eventHandle);
  153. next = directory.find('\\', pos = next + 1);
  154. }
  155. if (pos < directory.length())
  156. {
  157. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], directory.length() - pos))), eventHandle);
  158. }
  159. }
  160. }
  161. }
  162. // The try get folder directly by its full path
  163. if (!folder && directory.length())
  164. {
  165. folder = AWait(Windows::Storage::StorageFolder::GetFolderFromPathAsync(ConvertString(directory)), eventHandle);
  166. }
  167. // As a last sort, use app's local folder
  168. if (!folder)
  169. {
  170. folder = Windows::Storage::ApplicationData::Current->LocalFolder;
  171. }
  172. Windows::Storage::StorageFile^ file = nullptr;
  173. switch (*_Mode)
  174. {
  175. case 'a':
  176. file = AWait(folder->CreateFileAsync(ConvertString(filename), Windows::Storage::CreationCollisionOption::OpenIfExists), eventHandle);
  177. break;
  178. case 'w':
  179. file = AWait(folder->CreateFileAsync(ConvertString(filename), Windows::Storage::CreationCollisionOption::ReplaceExisting), eventHandle);
  180. break;
  181. case 'r':
  182. file = AWait(folder->GetFileAsync(ConvertString(filename)), eventHandle);
  183. break;
  184. }
  185. if (file)
  186. {
  187. *pFile = new WRT_FILE(AWait(file->OpenAsync(w ? Windows::Storage::FileAccessMode::ReadWrite : Windows::Storage::FileAccessMode::Read), eventHandle), r, w, b);
  188. }
  189. }
  190. catch (Platform::AccessDeniedException^)
  191. {
  192. return EACCES;
  193. }
  194. catch (Platform::Exception^)
  195. {
  196. return EIO;
  197. }
  198. return 0;
  199. }
  200. extern "C"
  201. WRT_FILE* WRT_fopen(const char * _Filename, const char * _Mode)
  202. {
  203. WRT_FILE* ret;
  204. int err = WRT_fopen_s(&ret, _Filename, _Mode);
  205. _set_errno(err);
  206. return err ? nullptr : ret;
  207. }
  208. extern "C"
  209. int WRT_fclose(WRT_FILE * _File)
  210. {
  211. if (!_File || _File->sig != _SIGNATURE) return fclose((FILE*)_File);
  212. delete _File;
  213. return 0;
  214. }
  215. extern "C"
  216. int WRT_feof(WRT_FILE * _File)
  217. {
  218. if (!_File || _File->sig != _SIGNATURE) return feof((FILE*)_File);
  219. STATSTG st;
  220. ULARGE_INTEGER uli;
  221. CriticalSection cs(_File->cs);
  222. if (SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, &uli)) &&
  223. SUCCEEDED(_File->stream->Stat(&st, STATFLAG_NONAME)))
  224. return uli.QuadPart >= st.cbSize.QuadPart;
  225. else
  226. return 1;
  227. }
  228. extern "C"
  229. int WRT_fseeki64(WRT_FILE * _File, long long _Offset, int _Origin)
  230. {
  231. if (!_File || _File->sig != _SIGNATURE) return _fseeki64((FILE*)_File, _Offset, _Origin);
  232. CriticalSection cs(_File->cs);
  233. LARGE_INTEGER liOffset;
  234. liOffset.QuadPart = _Offset;
  235. return SUCCEEDED(_File->stream->Seek(liOffset, _Origin, NULL)) ? 0 : -1;
  236. }
  237. extern "C"
  238. int WRT_fseek(WRT_FILE * _File, long _Offset, int _Origin)
  239. {
  240. return WRT_fseeki64(_File, _Offset, _Origin);
  241. }
  242. extern "C"
  243. long long WRT_ftelli64(WRT_FILE * _File)
  244. {
  245. if (!_File || _File->sig != _SIGNATURE) return _ftelli64((FILE*)_File);
  246. CriticalSection cs(_File->cs);
  247. unsigned long long pos;
  248. return SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, (PULARGE_INTEGER)&pos)) ? pos : -1;
  249. }
  250. extern "C"
  251. size_t WRT_ftell(WRT_FILE * _File)
  252. {
  253. return (size_t)WRT_ftelli64(_File);
  254. }
  255. extern "C"
  256. size_t WRT_fread(void * _DstBuf, size_t _ElementSize, size_t _Count, WRT_FILE * _File)
  257. {
  258. if (!_File || _File->sig != _SIGNATURE) return fread(_DstBuf, _ElementSize, _Count, (FILE*)_File);
  259. if (!_File->readable || _ElementSize == 0 || _Count == 0 || !_DstBuf) return 0;
  260. CriticalSection cs(_File->cs);
  261. unsigned long cbRead;
  262. return SUCCEEDED(_File->stream->Read(_DstBuf, _ElementSize * _Count, &cbRead)) ? cbRead / _ElementSize : 0;
  263. }
  264. extern "C"
  265. size_t WRT_fwrite(const void * _Str, size_t _Size, size_t _Count, WRT_FILE * _File)
  266. {
  267. if (!_File || _File->sig != _SIGNATURE) return fwrite(_Str, _Size, _Count, (FILE*)_File);
  268. if (!_File->writable || !_Str || _Size == 0 || _Count == 0) return 0;
  269. CriticalSection cs(_File->cs);
  270. unsigned long cbWrite;
  271. return SUCCEEDED(_File->stream->Write(_Str, _Size * _Count, &cbWrite)) ? cbWrite / _Size : 0;
  272. }
  273. extern "C"
  274. int WRT_fflush(WRT_FILE * _File)
  275. {
  276. if (!_File || _File->sig != _SIGNATURE) return fflush((FILE*)_File);
  277. if (!_File->writable) return 0;
  278. CriticalSection cs(_File->cs);
  279. return SUCCEEDED(_File->stream->Commit(STGC_DEFAULT)) ? 0 : EOF;
  280. }
  281. static int WRT_fgetc_nolock(WRT_FILE * _File)
  282. {
  283. unsigned long cbRead;
  284. unsigned char buf;
  285. return _File->stream->Read(&buf, 1, &cbRead) == S_OK ? buf : EOF;
  286. }
  287. extern "C"
  288. int WRT_fgetc(WRT_FILE * _File)
  289. {
  290. if (!_File || _File->sig != _SIGNATURE) return fgetc((FILE*)_File);
  291. CriticalSection cs(_File->cs);
  292. return _File->readable ? WRT_fgetc_nolock(_File) : EOF;
  293. }
  294. extern "C"
  295. char* WRT_fgets(char * _Buf, int _MaxCount, WRT_FILE * _File)
  296. {
  297. if (!_File || _File->sig != _SIGNATURE) return fgets(_Buf, _MaxCount, (FILE*)_File);
  298. if (!_File->readable || !_Buf || _MaxCount <= 0) return nullptr;
  299. CriticalSection cs(_File->cs);
  300. int n = 0, flag = 0, ch;
  301. while (n < _MaxCount - 1 && EOF != (ch = WRT_fgetc_nolock(_File)))
  302. {
  303. if (flag)
  304. {
  305. if (ch != '\n')
  306. _Buf[n++] = '\r';
  307. flag = 0;
  308. }
  309. if (ch != '\r')
  310. {
  311. _Buf[n++] = ch;
  312. if (ch == '\n') break;
  313. }
  314. else
  315. flag = 1;
  316. }
  317. if (n > 0)
  318. {
  319. _Buf[n] = '\0';
  320. return _Buf;
  321. }
  322. else
  323. return nullptr;
  324. }
  325. extern "C"
  326. int WRT_fputc(int _Ch, WRT_FILE * _File)
  327. {
  328. if (!_File || _File->sig != _SIGNATURE) return fputc(_Ch, (FILE*)_File);
  329. CriticalSection cs(_File->cs);
  330. unsigned long cbWrite;
  331. return _File->writable && _File->stream->Write(&_Ch, 1, &cbWrite) == S_OK ? cbWrite : EOF;
  332. }
  333. extern "C"
  334. int WRT_fputs(const char * _Str, WRT_FILE * _File)
  335. {
  336. if (!_File || _File->sig != _SIGNATURE) return fputs(_Str, (FILE*)_File);
  337. if (!_File->writable || !_Str) return EOF;
  338. const char *start = _Str;
  339. int length = strlen(_Str);
  340. unsigned long cbWrite;
  341. const char crlf[] = { '\r', '\n' };
  342. CriticalSection cs(_File->cs);
  343. while (true)
  344. {
  345. const char *ptr = start;
  346. while (*ptr && *ptr != '\n') ptr++;
  347. if (_File->stream->Write(start, ptr - start, &cbWrite) != S_OK)
  348. return EOF;
  349. if (*ptr == '\n')
  350. {
  351. if (_File->stream->Write(crlf, 2, &cbWrite) != S_OK)
  352. return EOF;
  353. else
  354. start = ptr + 1;
  355. }
  356. else
  357. break;
  358. }
  359. return length;
  360. }