AppSettingsWindow.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 bool showS3Settings;
  19. [NonSerialized] private string s3Bucket, s3Region, s3AccessKey, s3SecretKey, s3SessionToken;
  20. private const string TestUrlExample = @"<key>TestUserID</key>
  21. <string>https://example.com/test/</string>";
  22. [MenuItem("AppSettings/Open Settings")]
  23. public static void Open()
  24. {
  25. var window = GetWindow<AppSettingsWindow>("AppSettings");
  26. window.minSize = new Vector2(560, 420);
  27. window.LoadSettings();
  28. window.Show();
  29. }
  30. private void OnEnable()
  31. {
  32. showUsageHelp = true;
  33. LoadSettings();
  34. }
  35. private void LoadSettings()
  36. {
  37. settings = AppHelpProjectSettings.LoadOrCreateAppSettings();
  38. addressError = null;
  39. try
  40. {
  41. appAddress = string.IsNullOrEmpty(settings.AppAddress)
  42. ? string.Empty : ClientCrypto.DecryptString(settings.AppAddress);
  43. }
  44. catch (Exception)
  45. {
  46. appAddress = string.Empty;
  47. addressError = "Failed to decrypt AppAddress. Enter the plain-text address again and save.";
  48. }
  49. appChannel = settings.AppChannel;
  50. privacyUrl = settings.PrivacyUrl;
  51. downloadUrl = settings.DownloadUrl;
  52. gameSceneName = settings.GameSceneName;
  53. hotPatchAssembly = HotPatchAssemblySelection.Find(settings.HotPatchAssemblyName);
  54. var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings();
  55. facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null;
  56. appName = appId = clientToken = string.Empty;
  57. if (facebook == null) return;
  58. facebook.Update();
  59. appIndex = Mathf.Max(0, facebook.FindProperty("selectedAppIndex").intValue);
  60. appName = ReadFacebookValue("appLabels");
  61. appId = ReadFacebookValue("appIds");
  62. clientToken = ReadFacebookValue("clientTokens");
  63. }
  64. private string ReadFacebookValue(string name)
  65. {
  66. var property = facebook.FindProperty(name);
  67. return appIndex < property.arraySize
  68. ? property.GetArrayElementAtIndex(appIndex).stringValue : string.Empty;
  69. }
  70. private void WriteFacebookValue(string name, string value)
  71. {
  72. var property = facebook.FindProperty(name);
  73. while (property.arraySize <= appIndex)
  74. {
  75. var index = property.arraySize;
  76. property.arraySize++;
  77. property.GetArrayElementAtIndex(index).stringValue = string.Empty;
  78. }
  79. property.GetArrayElementAtIndex(appIndex).stringValue = value;
  80. }
  81. private void OnGUI()
  82. {
  83. using (new FontSizeScope(2))
  84. DrawWindow();
  85. }
  86. private void DrawWindow()
  87. {
  88. scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
  89. DrawHybridCLRSetup();
  90. EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel);
  91. if (facebook == null)
  92. EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error);
  93. using (new EditorGUI.DisabledScope(facebook == null))
  94. {
  95. appName = EditorGUILayout.TextField("Facebook AppName", appName);
  96. appId = EditorGUILayout.TextField("Facebook AppID", appId);
  97. clientToken = EditorGUILayout.TextField("Client Token", clientToken);
  98. }
  99. EditorGUILayout.Space();
  100. EditorGUILayout.LabelField("App", EditorStyles.boldLabel);
  101. EditorGUI.BeginChangeCheck();
  102. appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "Enter a plain-text address. It is encrypted when saved."), appAddress);
  103. if (EditorGUI.EndChangeCheck()) addressError = null;
  104. if (!string.IsNullOrEmpty(addressError))
  105. EditorGUILayout.HelpBox(addressError, MessageType.Error);
  106. appChannel = EditorGUILayout.TextField("AppChannel", appChannel);
  107. privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl);
  108. 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);
  109. hotPatchAssembly = (AssemblyDefinitionAsset)EditorGUILayout.ObjectField(
  110. new GUIContent("Hot Patch Assembly", "Select the game runtime asmdef. Save synchronizes the HybridCLR hot-update assembly settings."),
  111. hotPatchAssembly, typeof(AssemblyDefinitionAsset), false);
  112. EditorGUILayout.LabelField("Saved Assembly", settings.HotPatchAssemblyName);
  113. 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);
  114. EditorGUILayout.Space();
  115. using (new EditorGUILayout.HorizontalScope())
  116. {
  117. if (GUILayout.Button("Reload")) LoadSettings();
  118. if (GUILayout.Button("Save")) SaveSettings();
  119. using (new EditorGUI.DisabledScope(S3UploadController.IsUploading))
  120. if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源");
  121. }
  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. DrawS3Settings();
  141. }
  142. DrawUsageHelp();
  143. EditorGUILayout.EndScrollView();
  144. }
  145. private void ApplyResourceMode(bool localTesting)
  146. {
  147. try
  148. {
  149. HotPatchResourceActions.ApplyResources(localTesting);
  150. ShowNotification(new GUIContent(localTesting ? "已切换为本地资源测试" : "已恢复正式资源"));
  151. }
  152. catch (Exception exception)
  153. {
  154. Debug.LogException(exception);
  155. EditorUtility.DisplayDialog("切换资源失败", exception.Message, "确定");
  156. }
  157. }
  158. private void DrawHybridCLRSetup()
  159. {
  160. if (HybridCLRPackageSetup.IsInstalled) return;
  161. var installing = HybridCLRPackageSetup.IsInstalling;
  162. var message = installing ? "Installing the HybridCLR package. Wait for installation and compilation to finish." :
  163. "The HybridCLR package is required. Retry installation or add the following Git URL in Package Manager:\n" + HybridCLRPackageSetup.PackageUrl;
  164. if (!string.IsNullOrEmpty(HybridCLRPackageSetup.LastError)) message += "\n" + HybridCLRPackageSetup.LastError;
  165. EditorGUILayout.HelpBox(message, installing ? MessageType.Info : MessageType.Warning);
  166. using (new EditorGUI.DisabledScope(installing || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
  167. if (GUILayout.Button("Retry HybridCLR Installation")) HybridCLRPackageSetup.RetryInstallation();
  168. if (installing) Repaint();
  169. }
  170. private void DrawS3Settings()
  171. {
  172. showS3Settings = EditorGUILayout.Foldout(showS3Settings, "S3 上传配置(仅本机)", true);
  173. if (!showS3Settings) return;
  174. if (s3Bucket == null)
  175. {
  176. s3Bucket = S3UploadSettings.Bucket; s3Region = S3UploadSettings.Region;
  177. var credentials = S3UploadSettings.LoadCredentials();
  178. s3AccessKey = credentials.AccessKey ?? ""; s3SecretKey = credentials.SecretKey ?? ""; s3SessionToken = credentials.SessionToken ?? "";
  179. }
  180. s3Bucket = EditorGUILayout.TextField("Bucket", s3Bucket);
  181. s3Region = EditorGUILayout.TextField("Region", s3Region);
  182. s3AccessKey = EditorGUILayout.TextField("Access Key", s3AccessKey);
  183. s3SecretKey = EditorGUILayout.PasswordField("Secret Key", s3SecretKey);
  184. s3SessionToken = EditorGUILayout.PasswordField("Session Token (optional)", s3SessionToken);
  185. EditorGUILayout.HelpBox("凭据保存在本机 ~/.aws/credentials 的 app-runtimes 配置中,不进入项目或安装包。上传使用当前 DownloadUrl 的最后一级目录。", MessageType.Info);
  186. if (GUILayout.Button("保存 S3 配置"))
  187. {
  188. try
  189. {
  190. S3UploadSettings.Save(s3Bucket, s3Region, new S3UploadCredentials { AccessKey = s3AccessKey, SecretKey = s3SecretKey, SessionToken = s3SessionToken });
  191. ShowNotification(new GUIContent("S3 配置已保存到本机"));
  192. }
  193. catch (Exception exception) { ShowNotification(new GUIContent(exception.Message)); }
  194. }
  195. }
  196. private sealed class FontSizeScope : IDisposable
  197. {
  198. private readonly Dictionary<GUIStyle, int> originalSizes = new Dictionary<GUIStyle, int>();
  199. internal FontSizeScope(int increase)
  200. {
  201. var styles = new[]
  202. {
  203. EditorStyles.label, EditorStyles.boldLabel, EditorStyles.textField,
  204. EditorStyles.foldout, EditorStyles.helpBox, EditorStyles.textArea,
  205. GUI.skin.button
  206. };
  207. foreach (var style in styles)
  208. {
  209. if (originalSizes.ContainsKey(style)) continue;
  210. originalSizes.Add(style, style.fontSize);
  211. var defaultSize = style.font != null && style.font.fontSize > 0
  212. ? style.font.fontSize : 12;
  213. style.fontSize = (style.fontSize > 0 ? style.fontSize : defaultSize) + increase;
  214. }
  215. }
  216. public void Dispose()
  217. {
  218. foreach (var entry in originalSizes)
  219. entry.Key.fontSize = entry.Value;
  220. }
  221. }
  222. private void DrawUsageHelp()
  223. {
  224. EditorGUILayout.Space(12);
  225. showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "Test URL Setup (iOS)", true);
  226. if (showTestUrlHelp)
  227. {
  228. EditorGUILayout.HelpBox(
  229. "After exporting the iOS project, add TestUserID under the main App Target > Info in Xcode. Set its type to String and" +
  230. " its value to the complete test URL (for example, https://example.com/test/).\n" +
  231. "Alternatively, add the following entries directly inside the root <dict> in Info.plist.",
  232. MessageType.Info);
  233. DrawExample(TestUrlExample, "Copy Info.plist Example");
  234. EditorGUILayout.HelpBox(
  235. "iOS reads TestUserID at startup and uses the test URL if it is not empty. Rebuild and launch the app after changing it.\n" +
  236. "Remove the key or clear its value to restore the normal flow. TestUrl is always empty on Android and in the Unity Editor.",
  237. MessageType.None);
  238. }
  239. EditorGUILayout.Space(8);
  240. showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "使用注意事项", true);
  241. if (showUsageHelp)
  242. {
  243. EditorGUILayout.HelpBox(
  244. "1. 订阅 AppRuntimesEvents.OnPlatformOpen 事件,在回调中停止播放单机游戏的背景音乐。打开 WebView 时会触发该事件。\n\n" +
  245. "2. 操作步骤:Save >>> 一键打包资源 >>> 上传资源",
  246. MessageType.Info);
  247. }
  248. }
  249. private void DrawExample(string example, string copyLabel)
  250. {
  251. var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
  252. var height = style.CalcHeight(new GUIContent(example), Mathf.Max(200, position.width - 40));
  253. EditorGUILayout.SelectableLabel(example, style, GUILayout.Height(height));
  254. if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel))
  255. {
  256. EditorGUIUtility.systemCopyBuffer = example;
  257. ShowNotification(new GUIContent("Example copied"));
  258. }
  259. }
  260. private void SaveSettings()
  261. {
  262. if (string.IsNullOrWhiteSpace(gameSceneName))
  263. {
  264. ShowNotification(new GUIContent("Enter a game scene name"));
  265. return;
  266. }
  267. if (!string.IsNullOrWhiteSpace(downloadUrl) && (!Uri.TryCreate(downloadUrl.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")))
  268. {
  269. ShowNotification(new GUIContent("The hot patch URL must be an absolute HTTP(S) URL"));
  270. return;
  271. }
  272. if (!string.IsNullOrEmpty(addressError)) return;
  273. string encryptedAddress;
  274. try
  275. {
  276. encryptedAddress = string.IsNullOrEmpty(appAddress)
  277. ? string.Empty : ClientCrypto.EncryptString(appAddress);
  278. }
  279. catch (Exception)
  280. {
  281. addressError = "Failed to encrypt AppAddress. Settings were not saved. Enter the address again and retry.";
  282. return;
  283. }
  284. try { HotPatchAssemblySelection.Save(settings, hotPatchAssembly); }
  285. catch (Exception exception)
  286. {
  287. ShowNotification(new GUIContent(exception.Message));
  288. Debug.LogError("[HotPatch] Settings were not saved: " + exception.Message);
  289. return;
  290. }
  291. Undo.RecordObject(settings, "Save AppSettings");
  292. settings.AppAddress = encryptedAddress;
  293. settings.AppChannel = appChannel;
  294. settings.PrivacyUrl = privacyUrl;
  295. settings.DownloadUrl = (downloadUrl ?? string.Empty).Trim();
  296. settings.GameSceneName = gameSceneName.Trim();
  297. EditorUtility.SetDirty(settings);
  298. if (facebook != null)
  299. {
  300. facebook.Update();
  301. WriteFacebookValue("appLabels", appName);
  302. WriteFacebookValue("appIds", appId);
  303. WriteFacebookValue("clientTokens", clientToken);
  304. facebook.ApplyModifiedProperties();
  305. EditorUtility.SetDirty(facebook.targetObject);
  306. }
  307. AssetDatabase.SaveAssets();
  308. ShowNotification(new GUIContent("Settings saved"));
  309. }
  310. }