create-android-project.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #!/usr/bin/env python3
  2. import os
  3. from argparse import ArgumentParser
  4. from pathlib import Path
  5. import re
  6. import shutil
  7. import sys
  8. import textwrap
  9. SDL_ROOT = Path(__file__).resolve().parents[1]
  10. def extract_sdl_version() -> str:
  11. """
  12. Extract SDL version from SDL3/SDL_version.h
  13. """
  14. with open(SDL_ROOT / "include/SDL3/SDL_version.h") as f:
  15. data = f.read()
  16. major = int(next(re.finditer(r"#define\s+SDL_MAJOR_VERSION\s+([0-9]+)", data)).group(1))
  17. minor = int(next(re.finditer(r"#define\s+SDL_MINOR_VERSION\s+([0-9]+)", data)).group(1))
  18. micro = int(next(re.finditer(r"#define\s+SDL_MICRO_VERSION\s+([0-9]+)", data)).group(1))
  19. return f"{major}.{minor}.{micro}"
  20. def replace_in_file(path: Path, regex_what: str, replace_with: str) -> None:
  21. with path.open("r") as f:
  22. data = f.read()
  23. new_data, count = re.subn(regex_what, replace_with, data)
  24. assert count > 0, f"\"{regex_what}\" did not match anything in \"{path}\""
  25. with open(path, "w") as f:
  26. f.write(new_data)
  27. def android_mk_use_prefab(path: Path) -> None:
  28. """
  29. Replace relative SDL inclusion with dependency on prefab package
  30. """
  31. with path.open() as f:
  32. data = "".join(line for line in f.readlines() if "# SDL" not in line)
  33. data, _ = re.subn("[\n]{3,}", "\n\n", data)
  34. newdata = data + textwrap.dedent("""
  35. # https://google.github.io/prefab/build-systems.html
  36. # Add the prefab modules to the import path.
  37. $(call import-add-path,/out)
  38. # Import SDL3 so we can depend on it.
  39. $(call import-module,prefab/SDL3)
  40. """)
  41. with path.open("w") as f:
  42. f.write(newdata)
  43. def cmake_mk_no_sdl(path: Path) -> None:
  44. """
  45. Don't add the source directories of SDL/SDL_image/SDL_mixer/...
  46. """
  47. with path.open() as f:
  48. lines = f.readlines()
  49. newlines: list[str] = []
  50. for line in lines:
  51. if "add_subdirectory(SDL" in line:
  52. while newlines[-1].startswith("#"):
  53. newlines = newlines[:-1]
  54. continue
  55. newlines.append(line)
  56. newdata, _ = re.subn("[\n]{3,}", "\n\n", "".join(newlines))
  57. with path.open("w") as f:
  58. f.write(newdata)
  59. def gradle_add_prefab_and_aar(path: Path, aar: str) -> None:
  60. with path.open() as f:
  61. data = f.read()
  62. data, count = re.subn("android {", textwrap.dedent("""
  63. android {
  64. buildFeatures {
  65. prefab true
  66. }"""), data)
  67. assert count == 1
  68. data, count = re.subn("dependencies {", textwrap.dedent(f"""
  69. dependencies {{
  70. implementation files('libs/{aar}')"""), data)
  71. assert count == 1
  72. with path.open("w") as f:
  73. f.write(data)
  74. def gradle_add_package_name(path: Path, package_name: str) -> None:
  75. with path.open() as f:
  76. data = f.read()
  77. data, count = re.subn("org.libsdl.app", package_name, data)
  78. assert count >= 1
  79. with path.open("w") as f:
  80. f.write(data)
  81. def main() -> int:
  82. description = "Create a simple Android gradle project from input sources."
  83. epilog = "You need to manually copy a prebuilt SDL3 Android archive into the project tree when using the aar variant."
  84. parser = ArgumentParser(description=description, epilog=epilog, allow_abbrev=False)
  85. parser.add_argument("package_name", metavar="PACKAGENAME", help="Android package name (e.g. com.yourcompany.yourapp)")
  86. parser.add_argument("sources", metavar="SOURCE", nargs="*", help="Source code of your application. The files are copied to the output directory.")
  87. parser.add_argument("--variant", choices=["copy", "symlink", "aar"], default="copy", help="Choose variant of SDL project (copy: copy SDL sources, symlink: symlink SDL sources, aar: use Android aar archive)")
  88. parser.add_argument("--output", "-o", default=SDL_ROOT / "build", type=Path, help="Location where to store the Android project")
  89. parser.add_argument("--version", default=None, help="SDL3 version to use as aar dependency (only used for aar variant)")
  90. args = parser.parse_args()
  91. if not args.sources:
  92. print("Reading source file paths from stdin (press CTRL+D to stop)")
  93. args.sources = [path for path in sys.stdin.read().strip().split() if path]
  94. if not args.sources:
  95. parser.error("No sources passed")
  96. if not os.getenv("ANDROID_HOME"):
  97. print("WARNING: ANDROID_HOME environment variable not set", file=sys.stderr)
  98. if not os.getenv("ANDROID_NDK_HOME"):
  99. print("WARNING: ANDROID_NDK_HOME environment variable not set", file=sys.stderr)
  100. args.sources = [Path(src) for src in args.sources]
  101. build_path = args.output / args.package_name
  102. # Remove the destination folder
  103. shutil.rmtree(build_path, ignore_errors=True)
  104. # Copy the Android project
  105. shutil.copytree(SDL_ROOT / "android-project", build_path)
  106. # Add the source files to the ndk-build and cmake projects
  107. replace_in_file(build_path / "app/jni/src/Android.mk", r"YourSourceHere\.c", " \\\n ".join(src.name for src in args.sources))
  108. replace_in_file(build_path / "app/jni/src/CMakeLists.txt", r"YourSourceHere\.c", "\n ".join(src.name for src in args.sources))
  109. # Remove placeholder source "YourSourceHere.c"
  110. (build_path / "app/jni/src/YourSourceHere.c").unlink()
  111. # Copy sources to output folder
  112. for src in args.sources:
  113. if not src.is_file():
  114. parser.error(f"\"{src}\" is not a file")
  115. shutil.copyfile(src, build_path / "app/jni/src" / src.name)
  116. sdl_project_files = (
  117. SDL_ROOT / "src",
  118. SDL_ROOT / "include",
  119. SDL_ROOT / "LICENSE.txt",
  120. SDL_ROOT / "README.md",
  121. SDL_ROOT / "Android.mk",
  122. SDL_ROOT / "CMakeLists.txt",
  123. SDL_ROOT / "cmake",
  124. )
  125. if args.variant == "copy":
  126. (build_path / "app/jni/SDL").mkdir(exist_ok=True, parents=True)
  127. for sdl_project_file in sdl_project_files:
  128. # Copy SDL project files and directories
  129. if sdl_project_file.is_dir():
  130. shutil.copytree(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  131. elif sdl_project_file.is_file():
  132. shutil.copyfile(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  133. elif args.variant == "symlink":
  134. (build_path / "app/jni/SDL").mkdir(exist_ok=True, parents=True)
  135. # Create symbolic links for all SDL project files
  136. for sdl_project_file in sdl_project_files:
  137. os.symlink(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  138. elif args.variant == "aar":
  139. if not args.version:
  140. args.version = extract_sdl_version()
  141. major = args.version.split(".")[0]
  142. aar = f"SDL{ major }-{ args.version }.aar"
  143. # Remove all SDL java classes
  144. shutil.rmtree(build_path / "app/src/main/java")
  145. # Use prefab to generate include-able files
  146. gradle_add_prefab_and_aar(build_path / "app/build.gradle", aar=aar)
  147. # Make sure to use the prefab-generated files and not SDL sources
  148. android_mk_use_prefab(build_path / "app/jni/src/Android.mk")
  149. cmake_mk_no_sdl(build_path / "app/jni/CMakeLists.txt")
  150. aar_libs_folder = build_path / "app/libs"
  151. aar_libs_folder.mkdir(parents=True)
  152. with (aar_libs_folder / "copy-sdl-aars-here.txt").open("w") as f:
  153. f.write(f"Copy {aar} to this folder.\n")
  154. print(f"WARNING: copy { aar } to { aar_libs_folder }", file=sys.stderr)
  155. # Add the package name to build.gradle
  156. gradle_add_package_name(build_path / "app/build.gradle", args.package_name)
  157. # Create entry activity, subclassing SDLActivity
  158. activity = args.package_name[args.package_name.rfind(".") + 1:].capitalize() + "Activity"
  159. activity_path = build_path / "app/src/main/java" / args.package_name.replace(".", "/") / f"{activity}.java"
  160. activity_path.parent.mkdir(parents=True)
  161. with activity_path.open("w") as f:
  162. f.write(textwrap.dedent(f"""
  163. package {args.package_name};
  164. import org.libsdl.app.SDLActivity;
  165. public class {activity} extends SDLActivity
  166. {{
  167. }}
  168. """))
  169. # Add the just-generated activity to the Android manifest
  170. replace_in_file(build_path / "app/src/main/AndroidManifest.xml", 'name="SDLActivity"', f'name="{activity}"')
  171. # Update project and build
  172. print("To build and install to a device for testing, run the following:")
  173. print(f"cd {build_path}")
  174. print("./gradlew installDebug")
  175. return 0
  176. if __name__ == "__main__":
  177. raise SystemExit(main())