SDL_utils.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 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(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS)
  20. #include <unistd.h>
  21. #endif
  22. #include "joystick/SDL_joystick_c.h" // For SDL_GetGamepadTypeFromVIDPID()
  23. #ifdef SDL_PLATFORM_EMSCRIPTEN
  24. #include <emscripten.h>
  25. EMSCRIPTEN_KEEPALIVE void Emscripten_force_free(void *ptr)
  26. {
  27. free(ptr); // This should NOT be SDL_free()
  28. }
  29. #endif
  30. // Common utility functions that aren't in the public API
  31. int SDL_powerof2(int x)
  32. {
  33. int value;
  34. if (x <= 0) {
  35. // Return some sane value - we shouldn't hit this in our use cases
  36. return 1;
  37. }
  38. // This trick works for 32-bit values
  39. {
  40. SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32));
  41. }
  42. value = x;
  43. value -= 1;
  44. value |= value >> 1;
  45. value |= value >> 2;
  46. value |= value >> 4;
  47. value |= value >> 8;
  48. value |= value >> 16;
  49. value += 1;
  50. return value;
  51. }
  52. Uint32 SDL_CalculateGCD(Uint32 a, Uint32 b)
  53. {
  54. if (b == 0) {
  55. return a;
  56. }
  57. return SDL_CalculateGCD(b, (a % b));
  58. }
  59. // Algorithm adapted with thanks from John Cook's blog post:
  60. // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation
  61. void SDL_CalculateFraction(float x, int *numerator, int *denominator)
  62. {
  63. const int N = 1000;
  64. int a = 0, b = 1;
  65. int c = 1, d = 0;
  66. while (b <= N && d <= N) {
  67. float mediant = (float)(a + c) / (b + d);
  68. if (x == mediant) {
  69. if (b + d <= N) {
  70. *numerator = a + c;
  71. *denominator = b + d;
  72. } else if (d > b) {
  73. *numerator = c;
  74. *denominator = d;
  75. } else {
  76. *numerator = a;
  77. *denominator = b;
  78. }
  79. return;
  80. } else if (x > mediant) {
  81. a = a + c;
  82. b = b + d;
  83. } else {
  84. c = a + c;
  85. d = b + d;
  86. }
  87. }
  88. if (b > N) {
  89. *numerator = c;
  90. *denominator = d;
  91. } else {
  92. *numerator = a;
  93. *denominator = b;
  94. }
  95. }
  96. bool SDL_startswith(const char *string, const char *prefix)
  97. {
  98. if (string && prefix &&
  99. SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0) {
  100. return true;
  101. }
  102. return false;
  103. }
  104. bool SDL_endswith(const char *string, const char *suffix)
  105. {
  106. size_t string_length = string ? SDL_strlen(string) : 0;
  107. size_t suffix_length = suffix ? SDL_strlen(suffix) : 0;
  108. if (suffix_length > 0 && suffix_length <= string_length) {
  109. if (SDL_memcmp(string + string_length - suffix_length, suffix, suffix_length) == 0) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. }
  115. SDL_COMPILE_TIME_ASSERT(sizeof_object_id, sizeof(int) == sizeof(Uint32));
  116. Uint32 SDL_GetNextObjectID(void)
  117. {
  118. static SDL_AtomicInt last_id;
  119. Uint32 id = (Uint32)SDL_AtomicIncRef(&last_id) + 1;
  120. if (id == 0) {
  121. id = (Uint32)SDL_AtomicIncRef(&last_id) + 1;
  122. }
  123. return id;
  124. }
  125. static SDL_InitState SDL_objects_init;
  126. static SDL_HashTable *SDL_objects;
  127. bool SDL_object_validation = true;
  128. static void SDLCALL SDL_InvalidParamChecksChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  129. {
  130. bool validation_enabled = true;
  131. #ifndef OBJECT_VALIDATION_REQUIRED
  132. if (hint) {
  133. switch (*hint) {
  134. case '0':
  135. case '1':
  136. validation_enabled = false;
  137. break;
  138. case '2':
  139. validation_enabled = true;
  140. break;
  141. default:
  142. break;
  143. }
  144. }
  145. #endif // !OBJECT_VALIDATION_REQUIRED
  146. SDL_object_validation = validation_enabled;
  147. }
  148. static Uint32 SDLCALL SDL_HashObject(void *unused, const void *key)
  149. {
  150. return (Uint32)(uintptr_t)key;
  151. }
  152. static bool SDL_KeyMatchObject(void *unused, const void *a, const void *b)
  153. {
  154. return (a == b);
  155. }
  156. void SDL_SetObjectValid(void *object, SDL_ObjectType type, bool valid)
  157. {
  158. SDL_assert(object != NULL);
  159. if (SDL_ShouldInit(&SDL_objects_init)) {
  160. SDL_objects = SDL_CreateHashTable(0, true, SDL_HashObject, SDL_KeyMatchObject, NULL, NULL);
  161. const bool initialized = (SDL_objects != NULL);
  162. SDL_SetInitialized(&SDL_objects_init, initialized);
  163. if (!initialized) {
  164. return;
  165. }
  166. SDL_AddHintCallback(SDL_HINT_INVALID_PARAM_CHECKS, SDL_InvalidParamChecksChanged, NULL);
  167. }
  168. if (valid) {
  169. SDL_InsertIntoHashTable(SDL_objects, object, (void *)(uintptr_t)type, true);
  170. } else {
  171. SDL_RemoveFromHashTable(SDL_objects, object);
  172. }
  173. }
  174. bool SDL_FindObject(void *object, SDL_ObjectType type)
  175. {
  176. const void *object_type;
  177. if (!SDL_FindInHashTable(SDL_objects, object, &object_type)) {
  178. return false;
  179. }
  180. return (((SDL_ObjectType)(uintptr_t)object_type) == type);
  181. }
  182. typedef struct GetOneObjectData
  183. {
  184. const SDL_ObjectType type;
  185. void **objects;
  186. const int count;
  187. int num_objects;
  188. } GetOneObjectData;
  189. static bool SDLCALL GetOneObject(void *userdata, const SDL_HashTable *table, const void *object, const void *object_type)
  190. {
  191. GetOneObjectData *data = (GetOneObjectData *) userdata;
  192. if ((SDL_ObjectType)(uintptr_t)object_type == data->type) {
  193. if (data->num_objects < data->count) {
  194. data->objects[data->num_objects] = (void *)object;
  195. }
  196. ++data->num_objects;
  197. }
  198. return true; // keep iterating.
  199. }
  200. int SDL_GetObjects(SDL_ObjectType type, void **objects, int count)
  201. {
  202. GetOneObjectData data = { type, objects, count, 0 };
  203. SDL_IterateHashTable(SDL_objects, GetOneObject, &data);
  204. return data.num_objects;
  205. }
  206. static bool SDLCALL LogOneLeakedObject(void *userdata, const SDL_HashTable *table, const void *object, const void *object_type)
  207. {
  208. const char *type = "unknown object";
  209. switch ((SDL_ObjectType)(uintptr_t)object_type) {
  210. #define SDLOBJTYPECASE(typ, name) case SDL_OBJECT_TYPE_##typ: type = name; break
  211. SDLOBJTYPECASE(WINDOW, "SDL_Window");
  212. SDLOBJTYPECASE(RENDERER, "SDL_Renderer");
  213. SDLOBJTYPECASE(TEXTURE, "SDL_Texture");
  214. SDLOBJTYPECASE(JOYSTICK, "SDL_Joystick");
  215. SDLOBJTYPECASE(GAMEPAD, "SDL_Gamepad");
  216. SDLOBJTYPECASE(HAPTIC, "SDL_Haptic");
  217. SDLOBJTYPECASE(SENSOR, "SDL_Sensor");
  218. SDLOBJTYPECASE(HIDAPI_DEVICE, "hidapi device");
  219. SDLOBJTYPECASE(HIDAPI_JOYSTICK, "hidapi joystick");
  220. SDLOBJTYPECASE(THREAD, "thread");
  221. SDLOBJTYPECASE(TRAY, "SDL_Tray");
  222. #undef SDLOBJTYPECASE
  223. default: break;
  224. }
  225. SDL_LogDebug(SDL_LOG_CATEGORY_SYSTEM, "Leaked %s (%p)", type, object);
  226. return true; // keep iterating.
  227. }
  228. void SDL_SetObjectsInvalid(void)
  229. {
  230. if (SDL_ShouldQuit(&SDL_objects_init)) {
  231. // Log any leaked objects
  232. SDL_IterateHashTable(SDL_objects, LogOneLeakedObject, NULL);
  233. SDL_DestroyHashTable(SDL_objects);
  234. SDL_objects = NULL;
  235. SDL_SetInitialized(&SDL_objects_init, false);
  236. SDL_RemoveHintCallback(SDL_HINT_INVALID_PARAM_CHECKS, SDL_InvalidParamChecksChanged, NULL);
  237. }
  238. }
  239. static int SDL_URIDecode(const char *src, char *dst, int len)
  240. {
  241. int ri, wi, di;
  242. char decode = '\0';
  243. if (!src || !dst || len < 0) {
  244. return -1;
  245. }
  246. if (len == 0) {
  247. len = (int)SDL_strlen(src);
  248. }
  249. for (ri = 0, wi = 0, di = 0; ri < len && wi < len; ri += 1) {
  250. if (di == 0) {
  251. // start decoding
  252. if (src[ri] == '%') {
  253. decode = '\0';
  254. di += 1;
  255. continue;
  256. }
  257. // normal write
  258. dst[wi] = src[ri];
  259. wi += 1;
  260. } else if (di == 1 || di == 2) {
  261. char off = '\0';
  262. char isa = src[ri] >= 'a' && src[ri] <= 'f';
  263. char isA = src[ri] >= 'A' && src[ri] <= 'F';
  264. char isn = src[ri] >= '0' && src[ri] <= '9';
  265. if (!(isa || isA || isn)) {
  266. // not a hexadecimal
  267. int sri;
  268. for (sri = ri - di; sri <= ri; sri += 1) {
  269. dst[wi] = src[sri];
  270. wi += 1;
  271. }
  272. di = 0;
  273. continue;
  274. }
  275. // itsy bitsy magicsy
  276. if (isn) {
  277. off = 0 - '0';
  278. } else if (isa) {
  279. off = 10 - 'a';
  280. } else if (isA) {
  281. off = 10 - 'A';
  282. }
  283. decode |= (src[ri] + off) << (2 - di) * 4;
  284. if (di == 2) {
  285. dst[wi] = decode;
  286. wi += 1;
  287. di = 0;
  288. } else {
  289. di += 1;
  290. }
  291. }
  292. }
  293. dst[wi] = '\0';
  294. return wi;
  295. }
  296. int SDL_URIToLocal(const char *src, char *dst)
  297. {
  298. if (SDL_memcmp(src, "file:/", 6) == 0) {
  299. src += 6; // local file?
  300. } else if (SDL_strstr(src, ":/") != NULL) {
  301. return -1; // wrong scheme
  302. }
  303. bool local = src[0] != '/' || (src[0] != '\0' && src[1] == '/');
  304. // Check the hostname, if present. RFC 3986 states that the hostname component of a URI is not case-sensitive.
  305. if (!local && src[0] == '/' && src[2] != '/') {
  306. char *hostname_end = SDL_strchr(src + 1, '/');
  307. if (hostname_end) {
  308. const size_t src_len = hostname_end - (src + 1);
  309. size_t hostname_len;
  310. #if defined(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS)
  311. char hostname[257];
  312. if (gethostname(hostname, 255) == 0) {
  313. hostname[256] = '\0';
  314. hostname_len = SDL_strlen(hostname);
  315. if (hostname_len == src_len && SDL_strncasecmp(src + 1, hostname, src_len) == 0) {
  316. src = hostname_end + 1;
  317. local = true;
  318. }
  319. }
  320. #endif
  321. if (!local) {
  322. static const char *localhost = "localhost";
  323. hostname_len = SDL_strlen(localhost);
  324. if (hostname_len == src_len && SDL_strncasecmp(src + 1, localhost, src_len) == 0) {
  325. src = hostname_end + 1;
  326. local = true;
  327. }
  328. }
  329. }
  330. }
  331. if (local) {
  332. // Convert URI escape sequences to real characters
  333. if (src[0] == '/') {
  334. src++;
  335. } else {
  336. src--;
  337. }
  338. return SDL_URIDecode(src, dst, 0);
  339. }
  340. return -1;
  341. }
  342. bool SDL_IsURI(const char *uri)
  343. {
  344. /* A valid URI begins with a letter and is followed by any sequence of
  345. * letters, digits, '+', '.', or '-'.
  346. */
  347. if (!uri) {
  348. return false;
  349. }
  350. // The first character of the scheme must be a letter.
  351. if (!((*uri >= 'a' && *uri <= 'z') || (*uri >= 'A' && *uri <= 'Z'))) {
  352. return false;
  353. }
  354. /* If the colon is found before encountering the end of the string or
  355. * any invalid characters, the scheme can be considered valid.
  356. */
  357. while (*uri) {
  358. if (!((*uri >= 'a' && *uri <= 'z') ||
  359. (*uri >= 'A' && *uri <= 'Z') ||
  360. (*uri >= '0' && *uri <= '9') ||
  361. *uri == '+' || *uri == '-' || *uri == '.')) {
  362. return false;
  363. }
  364. if (*++uri == ':') {
  365. return true;
  366. }
  367. }
  368. return false;
  369. }
  370. // This is a set of per-thread persistent strings that we can return from the SDL API.
  371. // This is used for short strings that might persist past the lifetime of the object
  372. // they are related to.
  373. static SDL_TLSID SDL_string_storage;
  374. static void SDL_FreePersistentStrings( void *value )
  375. {
  376. SDL_HashTable *strings = (SDL_HashTable *)value;
  377. SDL_DestroyHashTable(strings);
  378. }
  379. const char *SDL_GetPersistentString(const char *string)
  380. {
  381. if (!string) {
  382. return NULL;
  383. }
  384. if (!*string) {
  385. return "";
  386. }
  387. SDL_HashTable *strings = (SDL_HashTable *)SDL_GetTLS(&SDL_string_storage);
  388. if (!strings) {
  389. strings = SDL_CreateHashTable(0, false, SDL_HashString, SDL_KeyMatchString, SDL_DestroyHashValue, NULL);
  390. if (!strings) {
  391. return NULL;
  392. }
  393. SDL_SetTLS(&SDL_string_storage, strings, SDL_FreePersistentStrings);
  394. }
  395. const char *result;
  396. if (!SDL_FindInHashTable(strings, string, (const void **)&result)) {
  397. char *new_string = SDL_strdup(string);
  398. if (!new_string) {
  399. return NULL;
  400. }
  401. // If the hash table insert fails, at least we can return the string we allocated
  402. SDL_InsertIntoHashTable(strings, new_string, new_string, false);
  403. result = new_string;
  404. }
  405. return result;
  406. }
  407. static int PrefixMatch(const char *a, const char *b)
  408. {
  409. int matchlen = 0;
  410. // Fixes the "HORI HORl Taiko No Tatsujin Drum Controller"
  411. if (SDL_strncmp(a, "HORI ", 5) == 0 && SDL_strncmp(b, "HORl ", 5) == 0) {
  412. return 5;
  413. }
  414. while (*a && *b) {
  415. if (SDL_tolower((unsigned char)*a++) == SDL_tolower((unsigned char)*b++)) {
  416. ++matchlen;
  417. } else {
  418. break;
  419. }
  420. }
  421. return matchlen;
  422. }
  423. char *SDL_CreateDeviceName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name, const char *default_name)
  424. {
  425. static struct
  426. {
  427. const char *prefix;
  428. const char *replacement;
  429. } replacements[] = {
  430. { "(Standard system devices) ", "" },
  431. { "8BitDo Tech Ltd", "8BitDo" },
  432. { "ASTRO Gaming", "ASTRO" },
  433. { "Bensussen Deutsch & Associates,Inc.(BDA)", "BDA" },
  434. { "Guangzhou Chicken Run Network Technology Co., Ltd.", "GameSir" },
  435. { "HORI CO.,LTD.", "HORI" },
  436. { "HORI CO.,LTD", "HORI" },
  437. { "Mad Catz Inc.", "Mad Catz" },
  438. { "Nintendo Co., Ltd.", "Nintendo" },
  439. { "NVIDIA Corporation ", "" },
  440. { "Performance Designed Products", "PDP" },
  441. { "QANBA USA, LLC", "Qanba" },
  442. { "QANBA USA,LLC", "Qanba" },
  443. { "Unknown ", "" },
  444. };
  445. char *name = NULL;
  446. size_t i, len;
  447. if (!vendor_name) {
  448. vendor_name = "";
  449. }
  450. if (!product_name) {
  451. product_name = "";
  452. }
  453. while (*vendor_name == ' ') {
  454. ++vendor_name;
  455. }
  456. while (*product_name == ' ') {
  457. ++product_name;
  458. }
  459. if (*vendor_name && *product_name) {
  460. len = (SDL_strlen(vendor_name) + 1 + SDL_strlen(product_name) + 1);
  461. name = (char *)SDL_malloc(len);
  462. if (name) {
  463. (void)SDL_snprintf(name, len, "%s %s", vendor_name, product_name);
  464. }
  465. } else if (*product_name) {
  466. name = SDL_strdup(product_name);
  467. } else if (vendor || product) {
  468. // Couldn't find a controller name, try to give it one based on device type
  469. switch (SDL_GetGamepadTypeFromVIDPID(vendor, product, NULL, true)) {
  470. case SDL_GAMEPAD_TYPE_XBOX360:
  471. name = SDL_strdup("Xbox 360 Controller");
  472. break;
  473. case SDL_GAMEPAD_TYPE_XBOXONE:
  474. name = SDL_strdup("Xbox One Controller");
  475. break;
  476. case SDL_GAMEPAD_TYPE_PS3:
  477. name = SDL_strdup("PS3 Controller");
  478. break;
  479. case SDL_GAMEPAD_TYPE_PS4:
  480. name = SDL_strdup("PS4 Controller");
  481. break;
  482. case SDL_GAMEPAD_TYPE_PS5:
  483. name = SDL_strdup("DualSense Wireless Controller");
  484. break;
  485. case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO:
  486. name = SDL_strdup("Nintendo Switch Pro Controller");
  487. break;
  488. default:
  489. len = (6 + 1 + 6 + 1);
  490. name = (char *)SDL_malloc(len);
  491. if (name) {
  492. (void)SDL_snprintf(name, len, "0x%.4x/0x%.4x", vendor, product);
  493. }
  494. break;
  495. }
  496. } else if (default_name) {
  497. name = SDL_strdup(default_name);
  498. }
  499. if (!name) {
  500. return NULL;
  501. }
  502. // Trim trailing whitespace
  503. for (len = SDL_strlen(name); (len > 0 && name[len - 1] == ' '); --len) {
  504. // continue
  505. }
  506. name[len] = '\0';
  507. // Compress duplicate spaces
  508. for (i = 0; i < (len - 1);) {
  509. if (name[i] == ' ' && name[i + 1] == ' ') {
  510. SDL_memmove(&name[i], &name[i + 1], (len - i));
  511. --len;
  512. } else {
  513. ++i;
  514. }
  515. }
  516. // Perform any manufacturer replacements
  517. for (i = 0; i < SDL_arraysize(replacements); ++i) {
  518. size_t prefixlen = SDL_strlen(replacements[i].prefix);
  519. if (SDL_strncasecmp(name, replacements[i].prefix, prefixlen) == 0) {
  520. size_t replacementlen = SDL_strlen(replacements[i].replacement);
  521. if (replacementlen <= prefixlen) {
  522. SDL_memcpy(name, replacements[i].replacement, replacementlen);
  523. SDL_memmove(name + replacementlen, name + prefixlen, (len - prefixlen) + 1);
  524. len -= (prefixlen - replacementlen);
  525. } else {
  526. // FIXME: Need to handle the expand case by reallocating the string
  527. }
  528. break;
  529. }
  530. }
  531. /* Remove duplicate manufacturer or product in the name
  532. * e.g. Razer Razer Raiju Tournament Edition Wired
  533. */
  534. for (i = 1; i < (len - 1); ++i) {
  535. int matchlen = PrefixMatch(name, &name[i]);
  536. while (matchlen > 0) {
  537. if (name[matchlen] == ' ' || name[matchlen] == '-') {
  538. SDL_memmove(name, name + matchlen + 1, len - matchlen);
  539. break;
  540. }
  541. --matchlen;
  542. }
  543. if (matchlen > 0) {
  544. // We matched the manufacturer's name and removed it
  545. break;
  546. }
  547. }
  548. return name;
  549. }
  550. void SDL_DebugLogBackend(const char *subsystem, const char *backend)
  551. {
  552. SDL_LogDebug(SDL_LOG_CATEGORY_SYSTEM, "SDL chose %s backend '%s'", subsystem, backend);
  553. }