SDL_windows.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINRT) || defined(SDL_PLATFORM_GDK)
  20. #include "SDL_windows.h"
  21. #include <objbase.h> /* for CoInitialize/CoUninitialize (Win32 only) */
  22. #ifdef HAVE_ROAPI_H
  23. #include <roapi.h> /* For RoInitialize/RoUninitialize (Win32 only) */
  24. #else
  25. typedef enum RO_INIT_TYPE
  26. {
  27. RO_INIT_SINGLETHREADED = 0,
  28. RO_INIT_MULTITHREADED = 1
  29. } RO_INIT_TYPE;
  30. #endif
  31. #ifndef _WIN32_WINNT_VISTA
  32. #define _WIN32_WINNT_VISTA 0x0600
  33. #endif
  34. #ifndef _WIN32_WINNT_WIN7
  35. #define _WIN32_WINNT_WIN7 0x0601
  36. #endif
  37. #ifndef _WIN32_WINNT_WIN8
  38. #define _WIN32_WINNT_WIN8 0x0602
  39. #endif
  40. #ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
  41. #define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
  42. #endif
  43. /* Sets an error message based on an HRESULT */
  44. int WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
  45. {
  46. TCHAR buffer[1024];
  47. char *message;
  48. TCHAR *p = buffer;
  49. DWORD c = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, 0,
  50. buffer, SDL_arraysize(buffer), NULL);
  51. buffer[c] = 0;
  52. /* kill CR/LF that FormatMessage() sticks at the end */
  53. while (*p) {
  54. if (*p == '\r') {
  55. *p = 0;
  56. break;
  57. }
  58. ++p;
  59. }
  60. message = WIN_StringToUTF8(buffer);
  61. SDL_SetError("%s%s%s", prefix ? prefix : "", prefix ? ": " : "", message);
  62. SDL_free(message);
  63. return -1;
  64. }
  65. /* Sets an error message based on GetLastError() */
  66. int WIN_SetError(const char *prefix)
  67. {
  68. return WIN_SetErrorFromHRESULT(prefix, GetLastError());
  69. }
  70. HRESULT
  71. WIN_CoInitialize(void)
  72. {
  73. /* SDL handles any threading model, so initialize with the default, which
  74. is compatible with OLE and if that doesn't work, try multi-threaded mode.
  75. If you need multi-threaded mode, call CoInitializeEx() before SDL_Init()
  76. */
  77. #ifdef SDL_PLATFORM_WINRT
  78. /* DLudwig: On WinRT, it is assumed that COM was initialized in main().
  79. CoInitializeEx is available (not CoInitialize though), however
  80. on WinRT, main() is typically declared with the [MTAThread]
  81. attribute, which, AFAIK, should initialize COM.
  82. */
  83. return S_OK;
  84. #elif defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  85. /* On Xbox, there's no need to call CoInitializeEx (and it's not implemented) */
  86. return S_OK;
  87. #else
  88. HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  89. if (hr == RPC_E_CHANGED_MODE) {
  90. hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  91. }
  92. /* S_FALSE means success, but someone else already initialized. */
  93. /* You still need to call CoUninitialize in this case! */
  94. if (hr == S_FALSE) {
  95. return S_OK;
  96. }
  97. return hr;
  98. #endif
  99. }
  100. void WIN_CoUninitialize(void)
  101. {
  102. #ifndef SDL_PLATFORM_WINRT
  103. CoUninitialize();
  104. #endif
  105. }
  106. #ifndef SDL_PLATFORM_WINRT
  107. FARPROC WIN_LoadComBaseFunction(const char *name)
  108. {
  109. static SDL_bool s_bLoaded;
  110. static HMODULE s_hComBase;
  111. if (!s_bLoaded) {
  112. s_hComBase = LoadLibraryEx(TEXT("combase.dll"), NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
  113. s_bLoaded = SDL_TRUE;
  114. }
  115. if (s_hComBase) {
  116. return GetProcAddress(s_hComBase, name);
  117. } else {
  118. return NULL;
  119. }
  120. }
  121. #endif
  122. HRESULT
  123. WIN_RoInitialize(void)
  124. {
  125. #ifdef SDL_PLATFORM_WINRT
  126. return S_OK;
  127. #else
  128. typedef HRESULT(WINAPI * RoInitialize_t)(RO_INIT_TYPE initType);
  129. RoInitialize_t RoInitializeFunc = (RoInitialize_t)WIN_LoadComBaseFunction("RoInitialize");
  130. if (RoInitializeFunc) {
  131. /* RO_INIT_SINGLETHREADED is equivalent to COINIT_APARTMENTTHREADED */
  132. HRESULT hr = RoInitializeFunc(RO_INIT_SINGLETHREADED);
  133. if (hr == RPC_E_CHANGED_MODE) {
  134. hr = RoInitializeFunc(RO_INIT_MULTITHREADED);
  135. }
  136. /* S_FALSE means success, but someone else already initialized. */
  137. /* You still need to call RoUninitialize in this case! */
  138. if (hr == S_FALSE) {
  139. return S_OK;
  140. }
  141. return hr;
  142. } else {
  143. return E_NOINTERFACE;
  144. }
  145. #endif
  146. }
  147. void WIN_RoUninitialize(void)
  148. {
  149. #ifndef SDL_PLATFORM_WINRT
  150. typedef void(WINAPI * RoUninitialize_t)(void);
  151. RoUninitialize_t RoUninitializeFunc = (RoUninitialize_t)WIN_LoadComBaseFunction("RoUninitialize");
  152. if (RoUninitializeFunc) {
  153. RoUninitializeFunc();
  154. }
  155. #endif
  156. }
  157. #if !defined(SDL_PLATFORM_WINRT) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  158. static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
  159. {
  160. OSVERSIONINFOEXW osvi;
  161. DWORDLONG const dwlConditionMask = VerSetConditionMask(
  162. VerSetConditionMask(
  163. VerSetConditionMask(
  164. 0, VER_MAJORVERSION, VER_GREATER_EQUAL),
  165. VER_MINORVERSION, VER_GREATER_EQUAL),
  166. VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  167. SDL_zero(osvi);
  168. osvi.dwOSVersionInfoSize = sizeof(osvi);
  169. osvi.dwMajorVersion = wMajorVersion;
  170. osvi.dwMinorVersion = wMinorVersion;
  171. osvi.wServicePackMajor = wServicePackMajor;
  172. return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
  173. }
  174. #endif
  175. // apply some static variables so we only call into the Win32 API once per process for each check.
  176. #if defined(SDL_PLATFORM_WINRT) || defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  177. #define CHECKWINVER(notdesktop_platform_result, test) return (notdesktop_platform_result);
  178. #else
  179. #define CHECKWINVER(notdesktop_platform_result, test) \
  180. static SDL_bool checked = SDL_FALSE; \
  181. static BOOL retval = FALSE; \
  182. if (!checked) { \
  183. retval = (test); \
  184. checked = SDL_TRUE; \
  185. } \
  186. return retval;
  187. #endif
  188. // this is the oldest thing we run on (and we may lose support for this in SDL3 at any time!),
  189. // so there's no "OrGreater" as that would always be TRUE. The other functions are here to
  190. // ask "can we support a specific feature?" but this function is here to ask "do we need to do
  191. // something different for an OS version we probably should abandon?" :)
  192. BOOL WIN_IsWindowsXP(void)
  193. {
  194. CHECKWINVER(FALSE, !WIN_IsWindowsVistaOrGreater() && IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0));
  195. }
  196. BOOL WIN_IsWindowsVistaOrGreater(void)
  197. {
  198. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0));
  199. }
  200. BOOL WIN_IsWindows7OrGreater(void)
  201. {
  202. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0));
  203. }
  204. BOOL WIN_IsWindows8OrGreater(void)
  205. {
  206. CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0));
  207. }
  208. #undef CHECKWINVER
  209. /*
  210. WAVExxxCAPS gives you 31 bytes for the device name, and just truncates if it's
  211. longer. However, since WinXP, you can use the WAVExxxCAPS2 structure, which
  212. will give you a name GUID. The full name is in the Windows Registry under
  213. that GUID, located here: HKLM\System\CurrentControlSet\Control\MediaCategories
  214. Note that drivers can report GUID_NULL for the name GUID, in which case,
  215. Windows makes a best effort to fill in those 31 bytes in the usual place.
  216. This info summarized from MSDN:
  217. http://web.archive.org/web/20131027093034/http://msdn.microsoft.com/en-us/library/windows/hardware/ff536382(v=vs.85).aspx
  218. Always look this up in the registry if possible, because the strings are
  219. different! At least on Win10, I see "Yeti Stereo Microphone" in the
  220. Registry, and a unhelpful "Microphone(Yeti Stereo Microph" in winmm. Sigh.
  221. (Also, DirectSound shouldn't be limited to 32 chars, but its device enum
  222. has the same problem.)
  223. WASAPI doesn't need this. This is just for DirectSound/WinMM.
  224. */
  225. char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
  226. {
  227. #if defined(SDL_PLATFORM_WINRT) || defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  228. return WIN_StringToUTF8(name); /* No registry access on WinRT/UWP and Xbox, go with what we've got. */
  229. #else
  230. static const GUID nullguid = { 0 };
  231. const unsigned char *ptr;
  232. char keystr[128];
  233. WCHAR *strw = NULL;
  234. SDL_bool rc;
  235. HKEY hkey;
  236. DWORD len = 0;
  237. char *retval = NULL;
  238. if (WIN_IsEqualGUID(guid, &nullguid)) {
  239. return WIN_StringToUTF8(name); /* No GUID, go with what we've got. */
  240. }
  241. ptr = (const unsigned char *)guid;
  242. (void)SDL_snprintf(keystr, sizeof(keystr),
  243. "System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  244. ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6],
  245. ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
  246. strw = WIN_UTF8ToString(keystr);
  247. rc = (RegOpenKeyExW(HKEY_LOCAL_MACHINE, strw, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS);
  248. SDL_free(strw);
  249. if (!rc) {
  250. return WIN_StringToUTF8(name); /* oh well. */
  251. }
  252. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, NULL, &len) == ERROR_SUCCESS);
  253. if (!rc) {
  254. RegCloseKey(hkey);
  255. return WIN_StringToUTF8(name); /* oh well. */
  256. }
  257. strw = (WCHAR *)SDL_malloc(len + sizeof(WCHAR));
  258. if (!strw) {
  259. RegCloseKey(hkey);
  260. return WIN_StringToUTF8(name); /* oh well. */
  261. }
  262. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE)strw, &len) == ERROR_SUCCESS);
  263. RegCloseKey(hkey);
  264. if (!rc) {
  265. SDL_free(strw);
  266. return WIN_StringToUTF8(name); /* oh well. */
  267. }
  268. strw[len / 2] = 0; /* make sure it's null-terminated. */
  269. retval = WIN_StringToUTF8(strw);
  270. SDL_free(strw);
  271. return retval ? retval : WIN_StringToUTF8(name);
  272. #endif /* if SDL_PLATFORM_WINRT / else */
  273. }
  274. BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b)
  275. {
  276. return SDL_memcmp(a, b, sizeof(*a)) == 0;
  277. }
  278. BOOL WIN_IsEqualIID(REFIID a, REFIID b)
  279. {
  280. return SDL_memcmp(a, b, sizeof(*a)) == 0;
  281. }
  282. void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
  283. {
  284. sdlrect->x = winrect->left;
  285. sdlrect->w = (winrect->right - winrect->left) + 1;
  286. sdlrect->y = winrect->top;
  287. sdlrect->h = (winrect->bottom - winrect->top) + 1;
  288. }
  289. void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
  290. {
  291. winrect->left = sdlrect->x;
  292. winrect->right = sdlrect->x + sdlrect->w - 1;
  293. winrect->top = sdlrect->y;
  294. winrect->bottom = sdlrect->y + sdlrect->h - 1;
  295. }
  296. BOOL WIN_IsRectEmpty(const RECT *rect)
  297. {
  298. /* Calculating this manually because UWP and Xbox do not support Win32 IsRectEmpty. */
  299. return (rect->right <= rect->left) || (rect->bottom <= rect->top);
  300. }
  301. /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
  302. /* *INDENT-OFF* */ /* clang-format off */
  303. static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  304. static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  305. /* *INDENT-ON* */ /* clang-format on */
  306. SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat)
  307. {
  308. if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
  309. return SDL_AUDIO_F32;
  310. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
  311. return SDL_AUDIO_S16;
  312. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
  313. return SDL_AUDIO_S32;
  314. } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  315. const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)waveformat;
  316. if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  317. return SDL_AUDIO_F32;
  318. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
  319. return SDL_AUDIO_S16;
  320. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  321. return SDL_AUDIO_S32;
  322. }
  323. }
  324. return 0;
  325. }
  326. int WIN_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar)
  327. {
  328. if (WIN_IsWindowsXP()) {
  329. dwFlags &= ~WC_ERR_INVALID_CHARS; // not supported before Vista. Without this flag, it will just replace bogus chars with U+FFFD. You're on your own, WinXP.
  330. }
  331. return WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar);
  332. }
  333. /* Win32-specific SDL_RunApp(), which does most of the SDL_main work,
  334. based on SDL_windows_main.c, placed in the public domain by Sam Lantinga 4/13/98 */
  335. #ifdef SDL_PLATFORM_WIN32
  336. #include <shellapi.h> /* CommandLineToArgvW() */
  337. /* Pop up an out of memory message, returns to Windows */
  338. static int OutOfMemory(void)
  339. {
  340. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Out of memory - aborting", NULL);
  341. return -1;
  342. }
  343. DECLSPEC int MINGW32_FORCEALIGN SDL_RunApp(int _argc, char* _argv[], SDL_main_func mainFunction, void * reserved)
  344. {
  345. /* Gets the arguments with GetCommandLine, converts them to argc and argv
  346. and calls SDL_main */
  347. LPWSTR *argvw;
  348. char **argv;
  349. int i, argc, result;
  350. (void)_argc; (void)_argv; (void)reserved;
  351. argvw = CommandLineToArgvW(GetCommandLineW(), &argc);
  352. if (!argvw) {
  353. return OutOfMemory();
  354. }
  355. /* Note that we need to be careful about how we allocate/free memory here.
  356. * If the application calls SDL_SetMemoryFunctions(), we can't rely on
  357. * SDL_free() to use the same allocator after SDL_main() returns.
  358. */
  359. /* Parse it into argv and argc */
  360. argv = (char **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv));
  361. if (!argv) {
  362. return OutOfMemory();
  363. }
  364. for (i = 0; i < argc; ++i) {
  365. DWORD len;
  366. char *arg = WIN_StringToUTF8W(argvw[i]);
  367. if (!arg) {
  368. return OutOfMemory();
  369. }
  370. len = (DWORD)SDL_strlen(arg);
  371. argv[i] = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len + 1);
  372. if (!argv[i]) {
  373. return OutOfMemory();
  374. }
  375. SDL_memcpy(argv[i], arg, len);
  376. SDL_free(arg);
  377. }
  378. argv[i] = NULL;
  379. LocalFree(argvw);
  380. SDL_SetMainReady();
  381. /* Run the application main() code */
  382. result = mainFunction(argc, argv);
  383. /* Free argv, to avoid memory leak */
  384. for (i = 0; i < argc; ++i) {
  385. HeapFree(GetProcessHeap(), 0, argv[i]);
  386. }
  387. HeapFree(GetProcessHeap(), 0, argv);
  388. return result;
  389. }
  390. #endif /* SDL_PLATFORM_WIN32 */
  391. #endif /* defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINRT) || defined(SDL_PLATFORM_GDK) */