SDL_utils.c 16 KB

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