create-android-project.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 = textwrap.dedent("""\
  84. You need to manually copy a prebuilt SDL3 Android archive into the project tree when using the aar variant.
  85. Any changes you have done to the sources in the Android project will be lost
  86. """)
  87. parser = ArgumentParser(description=description, epilog=epilog, allow_abbrev=False)
  88. parser.add_argument("package_name", metavar="PACKAGENAME", help="Android package name (e.g. com.yourcompany.yourapp)")
  89. parser.add_argument("sources", metavar="SOURCE", nargs="*", help="Source code of your application. The files are copied to the output directory.")
  90. 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)")
  91. parser.add_argument("--output", "-o", default=SDL_ROOT / "build", type=Path, help="Location where to store the Android project")
  92. parser.add_argument("--version", default=None, help="SDL3 version to use as aar dependency (only used for aar variant)")
  93. args = parser.parse_args()
  94. if not args.sources:
  95. print("Reading source file paths from stdin (press CTRL+D to stop)")
  96. args.sources = [path for path in sys.stdin.read().strip().split() if path]
  97. if not args.sources:
  98. parser.error("No sources passed")
  99. if not os.getenv("ANDROID_HOME"):
  100. print("WARNING: ANDROID_HOME environment variable not set", file=sys.stderr)
  101. if not os.getenv("ANDROID_NDK_HOME"):
  102. print("WARNING: ANDROID_NDK_HOME environment variable not set", file=sys.stderr)
  103. args.sources = [Path(src) for src in args.sources]
  104. build_path = args.output / args.package_name
  105. # Remove the destination folder
  106. shutil.rmtree(build_path, ignore_errors=True)
  107. # Copy the Android project
  108. shutil.copytree(SDL_ROOT / "android-project", build_path)
  109. # Add the source files to the ndk-build and cmake projects
  110. replace_in_file(build_path / "app/jni/src/Android.mk", r"YourSourceHere\.c", " \\\n ".join(src.name for src in args.sources))
  111. replace_in_file(build_path / "app/jni/src/CMakeLists.txt", r"YourSourceHere\.c", "\n ".join(src.name for src in args.sources))
  112. # Remove placeholder source "YourSourceHere.c"
  113. (build_path / "app/jni/src/YourSourceHere.c").unlink()
  114. # Copy sources to output folder
  115. for src in args.sources:
  116. if not src.is_file():
  117. parser.error(f"\"{src}\" is not a file")
  118. shutil.copyfile(src, build_path / "app/jni/src" / src.name)
  119. sdl_project_files = (
  120. SDL_ROOT / "src",
  121. SDL_ROOT / "include",
  122. SDL_ROOT / "LICENSE.txt",
  123. SDL_ROOT / "README.md",
  124. SDL_ROOT / "Android.mk",
  125. SDL_ROOT / "CMakeLists.txt",
  126. SDL_ROOT / "cmake",
  127. )
  128. if args.variant == "copy":
  129. (build_path / "app/jni/SDL").mkdir(exist_ok=True, parents=True)
  130. for sdl_project_file in sdl_project_files:
  131. # Copy SDL project files and directories
  132. if sdl_project_file.is_dir():
  133. shutil.copytree(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  134. elif sdl_project_file.is_file():
  135. shutil.copyfile(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  136. elif args.variant == "symlink":
  137. (build_path / "app/jni/SDL").mkdir(exist_ok=True, parents=True)
  138. # Create symbolic links for all SDL project files
  139. for sdl_project_file in sdl_project_files:
  140. os.symlink(sdl_project_file, build_path / "app/jni/SDL" / sdl_project_file.name)
  141. elif args.variant == "aar":
  142. if not args.version:
  143. args.version = extract_sdl_version()
  144. major = args.version.split(".")[0]
  145. aar = f"SDL{ major }-{ args.version }.aar"
  146. # Remove all SDL java classes
  147. shutil.rmtree(build_path / "app/src/main/java")
  148. # Use prefab to generate include-able files
  149. gradle_add_prefab_and_aar(build_path / "app/build.gradle", aar=aar)
  150. # Make sure to use the prefab-generated files and not SDL sources
  151. android_mk_use_prefab(build_path / "app/jni/src/Android.mk")
  152. cmake_mk_no_sdl(build_path / "app/jni/CMakeLists.txt")
  153. aar_libs_folder = build_path / "app/libs"
  154. aar_libs_folder.mkdir(parents=True)
  155. with (aar_libs_folder / "copy-sdl-aars-here.txt").open("w") as f:
  156. f.write(f"Copy {aar} to this folder.\n")
  157. print(f"WARNING: copy { aar } to { aar_libs_folder }", file=sys.stderr)
  158. # Add the package name to build.gradle
  159. gradle_add_package_name(build_path / "app/build.gradle", args.package_name)
  160. # Create entry activity, subclassing SDLActivity
  161. activity = args.package_name[args.package_name.rfind(".") + 1:].capitalize() + "Activity"
  162. activity_path = build_path / "app/src/main/java" / args.package_name.replace(".", "/") / f"{activity}.java"
  163. activity_path.parent.mkdir(parents=True)
  164. with activity_path.open("w") as f:
  165. f.write(textwrap.dedent(f"""
  166. package {args.package_name};
  167. import org.libsdl.app.SDLActivity;
  168. public class {activity} extends SDLActivity
  169. {{
  170. }}
  171. """))
  172. # Add the just-generated activity to the Android manifest
  173. replace_in_file(build_path / "app/src/main/AndroidManifest.xml", 'name="SDLActivity"', f'name="{activity}"')
  174. # Update project and build
  175. print("To build and install to a device for testing, run the following:")
  176. print(f"cd {build_path}")
  177. print("./gradlew installDebug")
  178. return 0
  179. if __name__ == "__main__":
  180. raise SystemExit(main())