SDL_windows.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  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(__WIN32__) || defined(__WINRT__) || defined(__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 __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(__XBOXONE__) || defined(__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 __WINRT__
  103. CoUninitialize();
  104. #endif
  105. }
  106. #ifndef __WINRT__
  107. void *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 __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 __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(__WINRT__) && !defined(__XBOXONE__) && !defined(__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. BOOL WIN_IsWindowsVistaOrGreater(void)
  176. {
  177. #if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)
  178. return TRUE;
  179. #else
  180. return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0);
  181. #endif
  182. }
  183. BOOL WIN_IsWindows7OrGreater(void)
  184. {
  185. #if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)
  186. return TRUE;
  187. #else
  188. return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0);
  189. #endif
  190. }
  191. BOOL WIN_IsWindows8OrGreater(void)
  192. {
  193. #if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)
  194. return TRUE;
  195. #else
  196. return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0);
  197. #endif
  198. }
  199. /*
  200. WAVExxxCAPS gives you 31 bytes for the device name, and just truncates if it's
  201. longer. However, since WinXP, you can use the WAVExxxCAPS2 structure, which
  202. will give you a name GUID. The full name is in the Windows Registry under
  203. that GUID, located here: HKLM\System\CurrentControlSet\Control\MediaCategories
  204. Note that drivers can report GUID_NULL for the name GUID, in which case,
  205. Windows makes a best effort to fill in those 31 bytes in the usual place.
  206. This info summarized from MSDN:
  207. http://web.archive.org/web/20131027093034/http://msdn.microsoft.com/en-us/library/windows/hardware/ff536382(v=vs.85).aspx
  208. Always look this up in the registry if possible, because the strings are
  209. different! At least on Win10, I see "Yeti Stereo Microphone" in the
  210. Registry, and a unhelpful "Microphone(Yeti Stereo Microph" in winmm. Sigh.
  211. (Also, DirectSound shouldn't be limited to 32 chars, but its device enum
  212. has the same problem.)
  213. WASAPI doesn't need this. This is just for DirectSound/WinMM.
  214. */
  215. char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
  216. {
  217. #if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)
  218. return WIN_StringToUTF8(name); /* No registry access on WinRT/UWP and Xbox, go with what we've got. */
  219. #else
  220. static const GUID nullguid = { 0 };
  221. const unsigned char *ptr;
  222. char keystr[128];
  223. WCHAR *strw = NULL;
  224. SDL_bool rc;
  225. HKEY hkey;
  226. DWORD len = 0;
  227. char *retval = NULL;
  228. if (WIN_IsEqualGUID(guid, &nullguid)) {
  229. return WIN_StringToUTF8(name); /* No GUID, go with what we've got. */
  230. }
  231. ptr = (const unsigned char *)guid;
  232. (void)SDL_snprintf(keystr, sizeof(keystr),
  233. "System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  234. ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6],
  235. ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
  236. strw = WIN_UTF8ToString(keystr);
  237. rc = (RegOpenKeyExW(HKEY_LOCAL_MACHINE, strw, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS);
  238. SDL_free(strw);
  239. if (!rc) {
  240. return WIN_StringToUTF8(name); /* oh well. */
  241. }
  242. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, NULL, &len) == ERROR_SUCCESS);
  243. if (!rc) {
  244. RegCloseKey(hkey);
  245. return WIN_StringToUTF8(name); /* oh well. */
  246. }
  247. strw = (WCHAR *)SDL_malloc(len + sizeof(WCHAR));
  248. if (strw == NULL) {
  249. RegCloseKey(hkey);
  250. return WIN_StringToUTF8(name); /* oh well. */
  251. }
  252. rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE)strw, &len) == ERROR_SUCCESS);
  253. RegCloseKey(hkey);
  254. if (!rc) {
  255. SDL_free(strw);
  256. return WIN_StringToUTF8(name); /* oh well. */
  257. }
  258. strw[len / 2] = 0; /* make sure it's null-terminated. */
  259. retval = WIN_StringToUTF8(strw);
  260. SDL_free(strw);
  261. return retval ? retval : WIN_StringToUTF8(name);
  262. #endif /* if __WINRT__ / else */
  263. }
  264. BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b)
  265. {
  266. return SDL_memcmp(a, b, sizeof(*a)) == 0;
  267. }
  268. BOOL WIN_IsEqualIID(REFIID a, REFIID b)
  269. {
  270. return SDL_memcmp(a, b, sizeof(*a)) == 0;
  271. }
  272. void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
  273. {
  274. sdlrect->x = winrect->left;
  275. sdlrect->w = (winrect->right - winrect->left) + 1;
  276. sdlrect->y = winrect->top;
  277. sdlrect->h = (winrect->bottom - winrect->top) + 1;
  278. }
  279. void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
  280. {
  281. winrect->left = sdlrect->x;
  282. winrect->right = sdlrect->x + sdlrect->w - 1;
  283. winrect->top = sdlrect->y;
  284. winrect->bottom = sdlrect->y + sdlrect->h - 1;
  285. }
  286. BOOL WIN_IsRectEmpty(const RECT *rect)
  287. {
  288. /* Calculating this manually because UWP and Xbox do not support Win32 IsRectEmpty. */
  289. return (rect->right <= rect->left) || (rect->bottom <= rect->top);
  290. }
  291. /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
  292. /* *INDENT-OFF* */ /* clang-format off */
  293. static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  294. static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  295. /* *INDENT-ON* */ /* clang-format on */
  296. SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat)
  297. {
  298. if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
  299. return SDL_AUDIO_F32SYS;
  300. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
  301. return SDL_AUDIO_S16SYS;
  302. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
  303. return SDL_AUDIO_S32SYS;
  304. } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  305. const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)waveformat;
  306. if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  307. return SDL_AUDIO_F32SYS;
  308. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
  309. return SDL_AUDIO_S16SYS;
  310. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  311. return SDL_AUDIO_S32SYS;
  312. }
  313. }
  314. return 0;
  315. }
  316. /* Win32-specific SDL_RunApp(), which does most of the SDL_main work,
  317. based on SDL_windows_main.c, placed in the public domain by Sam Lantinga 4/13/98 */
  318. #ifdef __WIN32__
  319. #include <shellapi.h> /* CommandLineToArgvW() */
  320. /* Pop up an out of memory message, returns to Windows */
  321. static int OutOfMemory(void)
  322. {
  323. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Out of memory - aborting", NULL);
  324. return -1;
  325. }
  326. DECLSPEC int SDL_RunApp(int _argc, char* _argv[], SDL_main_func mainFunction, void * reserved)
  327. {
  328. /* Gets the arguments with GetCommandLine, converts them to argc and argv
  329. and calls SDL_main */
  330. LPWSTR *argvw;
  331. char **argv;
  332. int i, argc, result;
  333. (void)_argc; (void)_argv; (void)reserved;
  334. argvw = CommandLineToArgvW(GetCommandLineW(), &argc);
  335. if (argvw == NULL) {
  336. return OutOfMemory();
  337. }
  338. /* Note that we need to be careful about how we allocate/free memory here.
  339. * If the application calls SDL_SetMemoryFunctions(), we can't rely on
  340. * SDL_free() to use the same allocator after SDL_main() returns.
  341. */
  342. /* Parse it into argv and argc */
  343. argv = (char **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv));
  344. if (argv == NULL) {
  345. return OutOfMemory();
  346. }
  347. for (i = 0; i < argc; ++i) {
  348. DWORD len;
  349. char *arg = WIN_StringToUTF8W(argvw[i]);
  350. if (arg == NULL) {
  351. return OutOfMemory();
  352. }
  353. len = (DWORD)SDL_strlen(arg);
  354. argv[i] = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len + 1);
  355. if (!argv[i]) {
  356. return OutOfMemory();
  357. }
  358. SDL_memcpy(argv[i], arg, len);
  359. SDL_free(arg);
  360. }
  361. argv[i] = NULL;
  362. LocalFree(argvw);
  363. SDL_SetMainReady();
  364. /* Run the application main() code */
  365. result = mainFunction(argc, argv);
  366. /* Free argv, to avoid memory leak */
  367. for (i = 0; i < argc; ++i) {
  368. HeapFree(GetProcessHeap(), 0, argv[i]);
  369. }
  370. HeapFree(GetProcessHeap(), 0, argv);
  371. return result;
  372. }
  373. #endif /* __WIN32__ */
  374. #endif /* defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) */
  375. /*
  376. * Public APIs
  377. */
  378. #ifndef SDL_VIDEO_DRIVER_WINDOWS
  379. #if defined(__WIN32__) || defined(__GDK__)
  380. int SDL_RegisterApp(const char *name, Uint32 style, void *hInst)
  381. {
  382. (void)name;
  383. (void)style;
  384. (void)hInst;
  385. return 0;
  386. }
  387. void SDL_UnregisterApp(void)
  388. {
  389. }
  390. void SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata)
  391. {
  392. }
  393. #endif /* __WIN32__ || __GDK__ */
  394. #if defined(__WIN32__) || defined(__WINGDK__)
  395. int SDL_Direct3D9GetAdapterIndex(SDL_DisplayID displayID)
  396. {
  397. (void)displayID;
  398. return 0; /* D3DADAPTER_DEFAULT */
  399. }
  400. SDL_bool SDL_DXGIGetOutputInfo(SDL_DisplayID displayID, int *adapterIndex, int *outputIndex)
  401. {
  402. (void)displayID;
  403. if (adapterIndex) {
  404. *adapterIndex = -1;
  405. }
  406. if (outputIndex) {
  407. *outputIndex = -1;
  408. }
  409. return SDL_FALSE;
  410. }
  411. #endif /* __WIN32__ || __WINGDK__ */
  412. #endif /* !SDL_VIDEO_DRIVER_WINDOWS */