UniWebViewPostBuildProcessor.Android.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. using UnityEngine;
  5. using UnityEditor.Android;
  6. // Shared utilities for Android assets copying functionality
  7. static class UniWebViewAndroidAssetsHelper {
  8. /// <summary>
  9. /// Copies configured asset folders to Android assets directory
  10. /// </summary>
  11. /// <param name="assetFolders">Array of folder names relative to Assets directory</param>
  12. /// <param name="targetAssetsPath">Target Android assets path</param>
  13. public static void CopyConfiguredAssets(string[] assetFolders, string targetAssetsPath) {
  14. if (assetFolders == null || assetFolders.Length == 0) {
  15. return; // No folders configured, skip copying
  16. }
  17. Debug.Log("<UniWebView> Copying configured asset folders to Android assets...");
  18. foreach (var folder in assetFolders) {
  19. if (string.IsNullOrWhiteSpace(folder)) {
  20. continue;
  21. }
  22. try {
  23. // Source: Assets/folder (relative to Assets directory)
  24. var sourceDir = Path.Combine(Application.dataPath, folder);
  25. // Target: targetAssetsPath/folder (preserve relative path structure)
  26. var targetDir = Path.Combine(targetAssetsPath, folder);
  27. if (!Directory.Exists(sourceDir)) {
  28. Debug.LogWarning($"<UniWebView> Source folder not found: {sourceDir}");
  29. continue;
  30. }
  31. // Create target directory if it doesn't exist
  32. var targetParent = Path.GetDirectoryName(targetDir);
  33. if (!Directory.Exists(targetParent)) {
  34. Directory.CreateDirectory(targetParent);
  35. }
  36. // Remove existing target directory to ensure clean copy
  37. if (Directory.Exists(targetDir)) {
  38. Directory.Delete(targetDir, true);
  39. }
  40. // Copy directory recursively
  41. CopyDirectoryRecursively(sourceDir, targetDir);
  42. Debug.Log($"<UniWebView> Successfully copied '{folder}' to Android assets");
  43. } catch (Exception e) {
  44. Debug.LogError($"<UniWebView> Failed to copy folder '{folder}': {e.Message}");
  45. }
  46. }
  47. }
  48. /// <summary>
  49. /// Recursively copies directory contents, excluding Unity .meta files
  50. /// </summary>
  51. /// <param name="sourceDir">Source directory path</param>
  52. /// <param name="targetDir">Target directory path</param>
  53. public static void CopyDirectoryRecursively(string sourceDir, string targetDir) {
  54. Directory.CreateDirectory(targetDir);
  55. // Copy all files except .meta files
  56. foreach (var file in Directory.GetFiles(sourceDir)) {
  57. var fileName = Path.GetFileName(file);
  58. // Skip Unity .meta files
  59. if (fileName.EndsWith(".meta")) {
  60. continue;
  61. }
  62. var targetFile = Path.Combine(targetDir, fileName);
  63. File.Copy(file, targetFile, true);
  64. }
  65. // Copy all subdirectories recursively
  66. foreach (var subDir in Directory.GetDirectories(sourceDir)) {
  67. var subDirName = Path.GetFileName(subDir);
  68. var targetSubDir = Path.Combine(targetDir, subDirName);
  69. CopyDirectoryRecursively(subDir, targetSubDir);
  70. }
  71. }
  72. }
  73. class UniWebViewPostBuildProcessor : IPostGenerateGradleAndroidProject
  74. {
  75. public int callbackOrder { get { return 1; } }
  76. public void OnPostGenerateGradleAndroidProject(string path) {
  77. Debug.Log("<UniWebView> UniWebView Post Build Script is patching manifest file and gradle file...");
  78. PatchAndroidManifest(path);
  79. PatchBuildGradle(path);
  80. PatchGradleProperty(path);
  81. CopyAndroidAssets(path);
  82. }
  83. private void PatchAndroidManifest(string root) {
  84. var manifestFilePath = GetManifestFilePath(root);
  85. var manifest = new UniWebViewAndroidManifest(manifestFilePath);
  86. var changed = false;
  87. Debug.Log("<UniWebView> Set hardware accelerated to enable smooth web view experience and HTML5 support like video and canvas.");
  88. changed = manifest.SetHardwareAccelerated() || changed;
  89. var settings = UniWebViewEditorSettings.GetOrCreateSettings();
  90. if (settings.usesCleartextTraffic) {
  91. changed = manifest.SetUsesCleartextTraffic() || changed;
  92. }
  93. if (settings.writeExternalStorage) {
  94. changed = manifest.AddWriteExternalStoragePermission() || changed;
  95. }
  96. if (settings.accessFineLocation) {
  97. changed = manifest.AddAccessFineLocationPermission() || changed;
  98. }
  99. if (settings.authCallbackUrls.Length > 0) {
  100. changed = manifest.AddAuthCallbacksIntentFilter(settings.authCallbackUrls) || changed;
  101. }
  102. if (settings.supportLINELogin) {
  103. changed = manifest.AddAuthCallbacksIntentFilter(new string[] { "lineauth://auth" }) || changed;
  104. }
  105. if (changed) {
  106. manifest.Save();
  107. }
  108. }
  109. private Version GetVersion(string versionStr)
  110. {
  111. if (UniWebViewEditorSettings.TryParseVersion(versionStr, out var version))
  112. {
  113. return version;
  114. }
  115. return null;
  116. }
  117. // Returns true if version >= minVersion
  118. public static bool IsAtLeastVersion(Version version, Version minVersion)
  119. {
  120. if (version == null || minVersion == null)
  121. {
  122. return false;
  123. }
  124. return version.CompareTo(minVersion) >= 0;
  125. }
  126. private void PatchBuildGradle(string root) {
  127. var gradleFilePath = GetGradleFilePath(root);
  128. var config = new UniWebViewGradleConfig(gradleFilePath);
  129. var settings = UniWebViewEditorSettings.GetOrCreateSettings();
  130. var kotlinPrefix = "implementation 'org.jetbrains.kotlin:kotlin-stdlib:";
  131. var kotlinVersion = String.IsNullOrWhiteSpace(settings.kotlinVersion)
  132. ? UniWebViewEditorSettings.defaultKotlinVersion : settings.kotlinVersion;
  133. var kotlinVersionParsed = GetVersion(kotlinVersion);
  134. var minKotlinVersion = GetVersion(UniWebViewEditorSettings.defaultKotlinVersion);
  135. if (IsAtLeastVersion(kotlinVersionParsed, minKotlinVersion) == false)
  136. {
  137. Debug.LogWarning($"<UniWebView> Kotlin version {kotlinVersion} is lower than supported minimum {UniWebViewEditorSettings.defaultKotlinVersion}, clamping to {UniWebViewEditorSettings.defaultKotlinVersion}.");
  138. kotlinVersion = UniWebViewEditorSettings.defaultKotlinVersion;
  139. }
  140. var browserPrefix = "implementation 'androidx.browser:browser:";
  141. var browserVersion = String.IsNullOrWhiteSpace(settings.androidBrowserVersion)
  142. ? UniWebViewEditorSettings.defaultAndroidBrowserVersion : settings.androidBrowserVersion;
  143. var browserVersionInSetting = GetVersion(browserVersion);
  144. var minBrowserVersionStr = UniWebViewEditorSettings.defaultAndroidBrowserVersion;
  145. var minBrowserVersion = GetVersion(minBrowserVersionStr);
  146. if (IsAtLeastVersion(browserVersionInSetting, minBrowserVersion) == false)
  147. {
  148. Debug.LogWarning($"<UniWebView> Browser version {browserVersion} is lower than supported minimum {minBrowserVersionStr}, clamping to {minBrowserVersionStr}.");
  149. browserVersion = minBrowserVersionStr;
  150. browserVersionInSetting = minBrowserVersion;
  151. }
  152. // Browser package >= 1.9.0 needs at least Gradle android plugin 8.9.1.
  153. var minBrowserForGradleCheck = new Version(1, 9, 0);
  154. if (IsAtLeastVersion(browserVersionInSetting, minBrowserForGradleCheck))
  155. {
  156. var gradleVersionStr = GetGradleVersion(root);
  157. if (gradleVersionStr == null)
  158. {
  159. Debug.LogWarning($"<UniWebView> Unable to check gradle version, going to let you change browser version to {browserVersion}.");
  160. }
  161. else
  162. {
  163. var gradleSemanticVersion = GetVersion(gradleVersionStr);
  164. var minGradleVersion = new Version(8, 9, 1);
  165. if (IsAtLeastVersion(gradleSemanticVersion, minGradleVersion) == false)
  166. {
  167. Debug.LogWarning($"<UniWebView> Gradle plugin version {gradleVersionStr} is lower than the recommended minimum {minGradleVersion} for androidx.browser >= 1.9.0. Build might fail; consider upgrading AGP.");
  168. }
  169. }
  170. }
  171. var androidXCorePrefix = "implementation 'androidx.core:core:";
  172. var androidXCoreVersion = String.IsNullOrWhiteSpace(settings.androidXCoreVersion)
  173. ? UniWebViewEditorSettings.defaultAndroidXCoreVersion : settings.androidXCoreVersion;
  174. var dependenciesNode = config.Root.FindChildNodeByName("dependencies");
  175. if (dependenciesNode != null) {
  176. // Add kotlin
  177. if (settings.addsKotlin) {
  178. // remove legacy kotlin stdlib variants to avoid duplicate classes
  179. dependenciesNode.RemoveContentNode("kotlin-stdlib-jdk7");
  180. dependenciesNode.RemoveContentNode("kotlin-stdlib-jdk8");
  181. var kotlinBomPrefix = "implementation platform('org.jetbrains.kotlin:kotlin-bom:";
  182. dependenciesNode.ReplaceContentOrAddStartsWith(kotlinBomPrefix, kotlinBomPrefix + kotlinVersion + "')");
  183. dependenciesNode.ReplaceContentOrAddStartsWith(kotlinPrefix, kotlinPrefix + kotlinVersion + "'");
  184. Debug.Log("<UniWebView> Updated Kotlin dependency and BOM in build.gradle.");
  185. }
  186. // Add browser package
  187. if (settings.addsAndroidBrowser) {
  188. dependenciesNode.ReplaceContentOrAddStartsWith(browserPrefix, browserPrefix + browserVersion + "'");
  189. Debug.Log("<UniWebView> Updated Browser dependency in build.gradle.");
  190. }
  191. // Add Android X Core package
  192. if (!settings.addsAndroidBrowser && settings.addsAndroidXCore) {
  193. // When adding android browser to the project, we don't need to add Android X Core package, since gradle resolves for it.
  194. dependenciesNode.ReplaceContentOrAddStartsWith(androidXCorePrefix, androidXCorePrefix + androidXCoreVersion + "'");
  195. Debug.Log("<UniWebView> Updated Android X Core dependency in build.gradle.");
  196. }
  197. } else {
  198. Debug.LogError("UniWebViewPostBuildProcessor didn't find the `dependencies` field in build.gradle.");
  199. Debug.LogError("Although we can continue to add a `dependencies`, make sure you have setup Gradle and the template correctly.");
  200. var newNode = new UniWebViewGradleNode("dependencies", config.Root);
  201. if (settings.addsKotlin) {
  202. var kotlinBomPrefix = "implementation platform('org.jetbrains.kotlin:kotlin-bom:";
  203. newNode.AppendContentNode(kotlinBomPrefix + kotlinVersion + "')");
  204. newNode.AppendContentNode(kotlinPrefix + kotlinVersion + "'");
  205. }
  206. if (settings.addsAndroidBrowser) {
  207. newNode.AppendContentNode(browserPrefix + browserVersion + "'");
  208. }
  209. if (settings.addsAndroidXCore) {
  210. newNode.AppendContentNode(androidXCorePrefix + androidXCoreVersion + "'");
  211. }
  212. newNode.AppendContentNode("implementation(name: 'UniWebView', ext:'aar')");
  213. config.Root.AppendChildNode(newNode);
  214. }
  215. if (settings.addsKotlin && !HasResolutionStrategy(config.Root)) {
  216. // Force Kotlin stdlib versions to avoid duplicate classes pulled by mixed transitive deps.
  217. var resolutionBlock =
  218. "configurations.all {\n" +
  219. " resolutionStrategy {\n" +
  220. " force 'org.jetbrains.kotlin:kotlin-stdlib:" + kotlinVersion + "',\n" +
  221. " 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:" + kotlinVersion + "',\n" +
  222. " 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:" + kotlinVersion + "',\n" +
  223. " 'org.jetbrains.kotlin:kotlin-stdlib-common:" + kotlinVersion + "'\n" +
  224. " }\n" +
  225. "}";
  226. config.Root.AppendChildNode(new UniWebViewGradleContentNode(resolutionBlock, config.Root));
  227. }
  228. config.Save();
  229. }
  230. private bool HasResolutionStrategy(UniWebViewGradleNode root)
  231. {
  232. var found = false;
  233. root.Each(node =>
  234. {
  235. if (node is UniWebViewGradleContentNode content && content.Name.Contains("resolutionStrategy"))
  236. {
  237. found = true;
  238. }
  239. });
  240. return found;
  241. }
  242. private void PatchGradleProperty(string root) {
  243. var gradlePropertyFilePath = GetGradlePropertyFilePath(root);
  244. var patcher =
  245. new UniWebViewGradlePropertyPatcher(gradlePropertyFilePath, UniWebViewEditorSettings.GetOrCreateSettings());
  246. patcher.Patch();
  247. }
  248. private string CombinePaths(string[] paths) {
  249. var path = "";
  250. foreach (var item in paths) {
  251. path = Path.Combine(path, item);
  252. }
  253. return path;
  254. }
  255. private string GetManifestFilePath(string root) {
  256. string[] comps = {root, "src", "main", "AndroidManifest.xml"};
  257. return CombinePaths(comps);
  258. }
  259. private string GetGradleFilePath(string root) {
  260. string[] comps = {root, "build.gradle"};
  261. return CombinePaths(comps);
  262. }
  263. private string GetGradlePropertyFilePath(string root) {
  264. #if UNITY_2019_3_OR_NEWER
  265. string[] compos = {root, "..", "gradle.properties"};
  266. #else
  267. string[] compos = {root, "gradle.properties"};
  268. #endif
  269. return CombinePaths(compos);
  270. }
  271. private string GetGradleVersion(string pathToBuiltProject)
  272. {
  273. var rootBuildGradle = Path.Combine(pathToBuiltProject, "..", "build.gradle");
  274. if (!File.Exists(rootBuildGradle))
  275. {
  276. Debug.LogError("Gradle root build file not found at: " + rootBuildGradle);
  277. return null;
  278. }
  279. var content = File.ReadAllText(rootBuildGradle);
  280. // Prefer the plugins {} block syntax (Unity 2022+ templates)
  281. var pluginMatch = Regex.Match(
  282. content,
  283. @"id\s+['""]com\.android\.(?:application|library)['""]\s+version\s+['""](?<version>[0-9]+\.[0-9]+(?:\.[0-9]+)?(?:-[^'""]+)?)['""]",
  284. RegexOptions.IgnoreCase);
  285. if (pluginMatch.Success)
  286. {
  287. var version = pluginMatch.Groups["version"].Value;
  288. Debug.Log("<UniWebView> Detected Android Gradle Plugin version (plugins block): " + version);
  289. return version;
  290. }
  291. // Fallback to buildscript classpath declaration (Unity 2021 and below)
  292. var classpathMatch = Regex.Match(
  293. content,
  294. @"classpath\s+['""]com\.android\.tools\.build:gradle:(?<version>[0-9]+\.[0-9]+(?:\.[0-9]+)?(?:-[^'""]+)?)['""]",
  295. RegexOptions.IgnoreCase);
  296. if (classpathMatch.Success)
  297. {
  298. var version = classpathMatch.Groups["version"].Value;
  299. Debug.Log("<UniWebView> Detected Android Gradle Plugin version (buildscript classpath): " + version);
  300. return version;
  301. }
  302. Debug.LogWarning("<UniWebView> Could not detect Android Gradle Plugin version from " + rootBuildGradle);
  303. return null;
  304. }
  305. private void CopyAndroidAssets(string projectPath) {
  306. var settings = UniWebViewEditorSettings.GetOrCreateSettings();
  307. var targetPath = Path.Combine(projectPath, "src", "main", "assets");
  308. UniWebViewAndroidAssetsHelper.CopyConfiguredAssets(settings.androidAssetsFolders, targetPath);
  309. }
  310. }