AppSettingsWindow.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEditorInternal;
  5. using UnityEngine;
  6. public sealed class AppSettingsWindow : EditorWindow
  7. {
  8. private AppSettings settings;
  9. private SerializedObject facebook;
  10. private int appIndex;
  11. private string appName, appId, clientToken;
  12. private string appAddress, appChannel, privacyUrl, downloadUrl, gameSceneName;
  13. private AssemblyDefinitionAsset hotPatchAssembly;
  14. private string addressError;
  15. private Vector2 scrollPosition;
  16. private bool showTestUrlHelp = false;
  17. private bool showUsageHelp = true;
  18. private const string TestUrlExample = @"<key>TestUserID</key>
  19. <string>https://example.com/test/</string>";
  20. [MenuItem("AppSettings/Open Settings", false, 0)]
  21. public static void Open()
  22. {
  23. var window = GetWindow<AppSettingsWindow>("AppSettings");
  24. window.minSize = new Vector2(560, 420);
  25. window.LoadSettings();
  26. window.Show();
  27. }
  28. private void OnEnable()
  29. {
  30. showUsageHelp = true;
  31. LoadSettings();
  32. }
  33. private void LoadSettings()
  34. {
  35. settings = AppHelpProjectSettings.LoadOrCreateAppSettings();
  36. addressError = null;
  37. try
  38. {
  39. appAddress = string.IsNullOrEmpty(settings.AppAddress)
  40. ? string.Empty : ClientCrypto.DecryptString(settings.AppAddress);
  41. }
  42. catch (Exception)
  43. {
  44. appAddress = string.Empty;
  45. addressError = "Failed to decrypt AppAddress. Enter the plain-text address again and save.";
  46. }
  47. appChannel = settings.AppChannel;
  48. privacyUrl = settings.PrivacyUrl;
  49. downloadUrl = settings.DownloadUrl;
  50. gameSceneName = settings.GameSceneName;
  51. hotPatchAssembly = HotPatchAssemblySelection.Find(settings.HotPatchAssemblyName);
  52. var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings();
  53. facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null;
  54. appName = appId = clientToken = string.Empty;
  55. if (facebook == null) return;
  56. facebook.Update();
  57. appIndex = Mathf.Max(0, facebook.FindProperty("selectedAppIndex").intValue);
  58. appName = ReadFacebookValue("appLabels");
  59. appId = ReadFacebookValue("appIds");
  60. clientToken = ReadFacebookValue("clientTokens");
  61. }
  62. private string ReadFacebookValue(string name)
  63. {
  64. var property = facebook.FindProperty(name);
  65. return appIndex < property.arraySize
  66. ? property.GetArrayElementAtIndex(appIndex).stringValue : string.Empty;
  67. }
  68. private void WriteFacebookValue(string name, string value)
  69. {
  70. var property = facebook.FindProperty(name);
  71. while (property.arraySize <= appIndex)
  72. {
  73. var index = property.arraySize;
  74. property.arraySize++;
  75. property.GetArrayElementAtIndex(index).stringValue = string.Empty;
  76. }
  77. property.GetArrayElementAtIndex(appIndex).stringValue = value;
  78. }
  79. private void OnGUI()
  80. {
  81. using (new FontSizeScope(2))
  82. DrawWindow();
  83. }
  84. private void DrawWindow()
  85. {
  86. scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
  87. DrawHybridCLRSetup();
  88. EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel);
  89. if (facebook == null)
  90. EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error);
  91. using (new EditorGUI.DisabledScope(facebook == null))
  92. {
  93. appName = EditorGUILayout.TextField("Facebook AppName", appName);
  94. appId = EditorGUILayout.TextField("Facebook AppID", appId);
  95. clientToken = EditorGUILayout.TextField("Client Token", clientToken);
  96. }
  97. EditorGUILayout.Space();
  98. EditorGUILayout.LabelField("App", EditorStyles.boldLabel);
  99. EditorGUI.BeginChangeCheck();
  100. appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "Enter a plain-text address. It is encrypted when saved."), appAddress);
  101. if (EditorGUI.EndChangeCheck()) addressError = null;
  102. if (!string.IsNullOrEmpty(addressError))
  103. EditorGUILayout.HelpBox(addressError, MessageType.Error);
  104. appChannel = EditorGUILayout.TextField("AppChannel", appChannel);
  105. privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl);
  106. downloadUrl = EditorGUILayout.TextField(new GUIContent("Hot Patch DownloadUrl", "HTTP(S) resource directory or full manifest.json URL. Use 资源构建/一键打包资源 to export the DLL and manifest."), downloadUrl);
  107. hotPatchAssembly = (AssemblyDefinitionAsset)EditorGUILayout.ObjectField(
  108. new GUIContent("Hot Patch Assembly", "Select the game runtime asmdef. Save adds the required AppRuntimes.Base and Unity.Advertisement.IosSupport references and synchronizes HybridCLR settings."),
  109. hotPatchAssembly, typeof(AssemblyDefinitionAsset), false);
  110. EditorGUILayout.LabelField("Saved Assembly", settings.HotPatchAssemblyName);
  111. gameSceneName = EditorGUILayout.TextField(new GUIContent("Game Scene Name", "Enter a unique scene name without .unity. It is used to build the scene bundle, which Launch opens at runtime."), gameSceneName);
  112. EditorGUILayout.Space();
  113. using (new EditorGUILayout.HorizontalScope())
  114. {
  115. if (GUILayout.Button("Reload")) LoadSettings();
  116. if (GUILayout.Button("Save")) SaveSettings();
  117. using (new EditorGUI.DisabledScope(!CanBuildResources))
  118. if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源");
  119. }
  120. var buildBlockReason = HotPatchAssemblySelection.BuildBlockReason(settings, hotPatchAssembly, gameSceneName);
  121. if (buildBlockReason != null) EditorGUILayout.HelpBox(buildBlockReason, MessageType.Info);
  122. using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
  123. {
  124. var latest = HotPatchResourceActions.LatestDirectory;
  125. using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(latest)))
  126. {
  127. using (new EditorGUILayout.HorizontalScope())
  128. {
  129. if (GUILayout.Button("使用本地资源测试")) ApplyResourceMode(true);
  130. if (GUILayout.Button("恢复正式资源")) ApplyResourceMode(false);
  131. }
  132. if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl);
  133. }
  134. EditorGUILayout.LabelField("启动资源模式", settings.UseLocalHotPatchResources ? "本地资源测试(跳过远程热更新)" : "正式资源(检查远程更新)");
  135. if (string.IsNullOrEmpty(latest))
  136. EditorGUILayout.HelpBox("没有当前平台、程序集和场景对应的完整打包资源,请先 Save,再执行一键打包资源。", MessageType.Info);
  137. else EditorGUILayout.LabelField("最近打包资源", System.IO.Path.GetFileName(latest));
  138. try { EditorGUILayout.LabelField("上传目标", "s3://" + S3UploadSettings.Bucket + "/" + S3ResourceUploader.TargetPrefix(downloadUrl) + "/"); }
  139. catch (ArgumentException) { EditorGUILayout.LabelField("上传目标", "请设置包含目录的 DownloadUrl"); }
  140. catch (Exception exception) { EditorGUILayout.HelpBox(exception.Message, MessageType.Error); }
  141. }
  142. DrawUsageHelp();
  143. EditorGUILayout.EndScrollView();
  144. }
  145. private bool CanBuildResources => HotPatchAssemblySelection.BuildBlockReason(settings, hotPatchAssembly, gameSceneName) == null
  146. && !S3UploadController.IsUploading && !HotPatchResourceActions.IsBuilding && !EditorApplication.isCompiling
  147. && !EditorApplication.isUpdating && !EditorApplication.isPlayingOrWillChangePlaymode && !BuildPipeline.isBuildingPlayer;
  148. private void ApplyResourceMode(bool localTesting)
  149. {
  150. try
  151. {
  152. HotPatchResourceActions.ApplyResources(localTesting);
  153. ShowNotification(new GUIContent(localTesting ? "已切换为本地资源测试" : "已恢复正式资源"));
  154. }
  155. catch (Exception exception)
  156. {
  157. Debug.LogException(exception);
  158. EditorUtility.DisplayDialog("切换资源失败", exception.Message, "确定");
  159. }
  160. }
  161. private void DrawHybridCLRSetup()
  162. {
  163. if (HybridCLRPackageSetup.IsInstalled) return;
  164. var installing = HybridCLRPackageSetup.IsInstalling;
  165. var message = installing ? "Installing the HybridCLR package. Wait for installation and compilation to finish." :
  166. "The HybridCLR package is required. Retry installation or add the following Git URL in Package Manager:\n" + HybridCLRPackageSetup.PackageUrl;
  167. if (!string.IsNullOrEmpty(HybridCLRPackageSetup.LastError)) message += "\n" + HybridCLRPackageSetup.LastError;
  168. EditorGUILayout.HelpBox(message, installing ? MessageType.Info : MessageType.Warning);
  169. using (new EditorGUI.DisabledScope(installing || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
  170. if (GUILayout.Button("Retry HybridCLR Installation")) HybridCLRPackageSetup.RetryInstallation();
  171. if (installing) Repaint();
  172. }
  173. private sealed class FontSizeScope : IDisposable
  174. {
  175. private readonly Dictionary<GUIStyle, int> originalSizes = new Dictionary<GUIStyle, int>();
  176. internal FontSizeScope(int increase)
  177. {
  178. var styles = new[]
  179. {
  180. EditorStyles.label, EditorStyles.boldLabel, EditorStyles.textField,
  181. EditorStyles.foldout, EditorStyles.helpBox, EditorStyles.textArea,
  182. GUI.skin.button
  183. };
  184. foreach (var style in styles)
  185. {
  186. if (originalSizes.ContainsKey(style)) continue;
  187. originalSizes.Add(style, style.fontSize);
  188. var defaultSize = style.font != null && style.font.fontSize > 0
  189. ? style.font.fontSize : 12;
  190. style.fontSize = (style.fontSize > 0 ? style.fontSize : defaultSize) + increase;
  191. }
  192. }
  193. public void Dispose()
  194. {
  195. foreach (var entry in originalSizes)
  196. entry.Key.fontSize = entry.Value;
  197. }
  198. }
  199. private void DrawUsageHelp()
  200. {
  201. EditorGUILayout.Space(12);
  202. showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "Test URL Setup (iOS)", true);
  203. if (showTestUrlHelp)
  204. {
  205. EditorGUILayout.HelpBox(
  206. "After exporting the iOS project, add TestUserID under the main App Target > Info in Xcode. Set its type to String and" +
  207. " its value to the complete test URL (for example, https://example.com/test/).\n" +
  208. "Alternatively, add the following entries directly inside the root <dict> in Info.plist.",
  209. MessageType.Info);
  210. DrawExample(TestUrlExample, "Copy Info.plist Example");
  211. EditorGUILayout.HelpBox(
  212. "iOS reads TestUserID at startup and uses the test URL if it is not empty. Rebuild and launch the app after changing it.\n" +
  213. "Remove the key or clear its value to restore the normal flow. TestUrl is always empty on Android and in the Unity Editor.",
  214. MessageType.None);
  215. }
  216. EditorGUILayout.Space(8);
  217. showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "使用注意事项", true);
  218. if (showUsageHelp)
  219. {
  220. EditorGUILayout.HelpBox(
  221. "1. 订阅 AppRuntimesEvents.OnPlatformOpen 事件,在回调中停止播放单机游戏的背景音乐。打开 WebView 时会触发该事件。\n\n" +
  222. "2. 操作步骤:Save >>> 一键打包资源 >>> 上传资源\n\n" +
  223. "3. 审核后热更,把 manifest_hot.json 替换成 manifest.json,然后刷新 S3 缓存。",
  224. MessageType.Info);
  225. }
  226. }
  227. private void DrawExample(string example, string copyLabel)
  228. {
  229. var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
  230. var height = style.CalcHeight(new GUIContent(example), Mathf.Max(200, position.width - 40));
  231. EditorGUILayout.SelectableLabel(example, style, GUILayout.Height(height));
  232. if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel))
  233. {
  234. EditorGUIUtility.systemCopyBuffer = example;
  235. ShowNotification(new GUIContent("Example copied"));
  236. }
  237. }
  238. private void SaveSettings()
  239. {
  240. if (!string.IsNullOrWhiteSpace(downloadUrl) && (!Uri.TryCreate(downloadUrl.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")))
  241. {
  242. ShowNotification(new GUIContent("The hot patch URL must be an absolute HTTP(S) URL"));
  243. return;
  244. }
  245. if (!string.IsNullOrEmpty(addressError)) return;
  246. string encryptedAddress;
  247. try
  248. {
  249. encryptedAddress = string.IsNullOrEmpty(appAddress)
  250. ? string.Empty : ClientCrypto.EncryptString(appAddress);
  251. }
  252. catch (Exception)
  253. {
  254. addressError = "Failed to encrypt AppAddress. Settings were not saved. Enter the address again and retry.";
  255. return;
  256. }
  257. try { HotPatchAssemblySelection.Save(settings, hotPatchAssembly); }
  258. catch (Exception exception)
  259. {
  260. ShowNotification(new GUIContent(exception.Message));
  261. Debug.LogError("[HotPatch] Settings were not saved: " + exception.Message);
  262. return;
  263. }
  264. Undo.RecordObject(settings, "Save AppSettings");
  265. settings.AppAddress = encryptedAddress;
  266. settings.AppChannel = appChannel;
  267. settings.PrivacyUrl = privacyUrl;
  268. settings.DownloadUrl = (downloadUrl ?? string.Empty).Trim();
  269. settings.GameSceneName = (gameSceneName ?? string.Empty).Trim();
  270. EditorUtility.SetDirty(settings);
  271. if (facebook != null)
  272. {
  273. facebook.Update();
  274. WriteFacebookValue("appLabels", appName);
  275. WriteFacebookValue("appIds", appId);
  276. WriteFacebookValue("clientTokens", clientToken);
  277. facebook.ApplyModifiedProperties();
  278. EditorUtility.SetDirty(facebook.targetObject);
  279. }
  280. AssetDatabase.SaveAssets();
  281. Repaint();
  282. ShowNotification(new GUIContent("Settings saved"));
  283. }
  284. }