create-android-project.py 8.8 KB

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