WinRTIO.cpp 11 KB

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