sort_controllers.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. #
  3. # Script to sort the game controller database entries in SDL_gamecontroller.c
  4. import re
  5. filename = "SDL_gamecontrollerdb.h"
  6. input = open(filename)
  7. output = open(filename + ".new", "w")
  8. parsing_controllers = False
  9. controllers = []
  10. controller_guids = {}
  11. sdk_conditionals = []
  12. split_pattern = re.compile(r'([^"]*")([^,]*,)([^,]*,)([^"]*)(".*)')
  13. def save_controller(line):
  14. global controllers
  15. match = split_pattern.match(line)
  16. entry = [ match.group(1), match.group(2), match.group(3) ]
  17. bindings = sorted(match.group(4).split(","))
  18. if (bindings[0] == ""):
  19. bindings.pop(0)
  20. entry.extend(",".join(bindings) + ",")
  21. entry.append(match.group(5))
  22. controllers.append(entry)
  23. if ',sdk' in line:
  24. sdk_conditionals.append(entry[1])
  25. def write_controllers():
  26. global controllers
  27. global controller_guids
  28. # Check for duplicates
  29. for entry in controllers:
  30. if (entry[1] in controller_guids and entry[1] not in sdk_conditionals):
  31. current_name = entry[2]
  32. existing_name = controller_guids[entry[1]][2]
  33. print("Warning: entry '%s' is duplicate of entry '%s'" % (current_name, existing_name))
  34. if (not current_name.startswith("(DUPE)")):
  35. entry[2] = "(DUPE) " + current_name
  36. if (not existing_name.startswith("(DUPE)")):
  37. controller_guids[entry[1]][2] = "(DUPE) " + existing_name
  38. controller_guids[entry[1]] = entry
  39. for entry in sorted(controllers, key=lambda entry: entry[2]+"-"+entry[1]):
  40. line = "".join(entry) + "\n"
  41. line = line.replace("\t", " ")
  42. if not line.endswith(",\n") and not line.endswith("*/\n"):
  43. print("Warning: '%s' is missing a comma at the end of the line" % (line))
  44. output.write(line)
  45. controllers = []
  46. controller_guids = {}
  47. for line in input:
  48. if (parsing_controllers):
  49. if (line.startswith("{")):
  50. output.write(line)
  51. elif (line.startswith(" NULL")):
  52. parsing_controllers = False
  53. write_controllers()
  54. output.write(line)
  55. elif (line.startswith("#if")):
  56. print("Parsing " + line.strip())
  57. output.write(line)
  58. elif (line.startswith("#endif")):
  59. write_controllers()
  60. output.write(line)
  61. else:
  62. save_controller(line)
  63. else:
  64. if (line.startswith("static const char *s_ControllerMappings")):
  65. parsing_controllers = True
  66. output.write(line)
  67. output.close()
  68. print("Finished writing %s.new" % filename)